我有这门课
class TimeSpentStats{
int manId;
String sessionId;
int userId;
Long timeStamp;
}
我有一个列表,我想获取最小时间戳和最大时间戳 从每个(manId、sessionId、userId)的列表中
例如,我有:
manId sessionId userId timeStamp
1 01F 5 1000
1 01F 5 1005
3 6Y 3 7
3 6Y 3 16
我需要 (1 01F 5) -> min = 1000 , max = 1005 对于 (3 6Y 3 ) -> min = 7 , max = 16
我需要在同一个类中添加 2 个属性吗? 如果我能做到这一点,有什么想法吗?谢谢
最佳答案
如果您有一个名为 list 的 TimeSpentStatus 列表,则以下算法应该执行您希望它执行的操作。
HashMap<String, Pair> statsList = new HashMap<String, Pair>();
for(TimeSpentStats stats : list){
// Constructs the combination of IDs that is used as the key to a Pair object
String statsStr = stats.manId + " " + stats.sessionId + " " + stats.userId;
if(statsList.containsKey(statsStr)){
// Update min and/or max time for the current combination as necessary
statsList.get(statsStr).minTime = Math.min(statsList.get(statsStr).minTime, stats.timeStamp);
statsList.get(statsStr).maxTime = Math.max(statsList.get(statsStr).maxTime, stats.timeStamp);
}else{
// Construct a new Pair for the ID combination and add max and min times
Pair p = new Pair();
p.maxTime = stats.timeStamp;
p.minTime = stats.timeStamp;
// Adds the new combination to the HashMap, which can now be updated in the if-statement
statsList.put(statsStr, p);
}
}
statsList 现在将包含每个组合的最大和最小时间,以 (userID + ""+ manID + ""+ sessionID) 作为键。然后,您将能够使用 statsList.get(userId + ""+ manId + ""+ sessionId) 获取特定组合的 Pair 对象(只要它当然存在)。
这是Pair类
class Pair{
public long minTime;
public long maxTime;
}
关于java - 从对象列表中获取最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26343140/