java - 从对象列表中获取最小值和最大值

标签 java list collections minim

我有这门课

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/

相关文章:

java - 使用给定的字段对象 id 而不是对象本身存储 JPA 实体

java - 将程序从 MATLAB 移植到 Java?

java - 使用提交按钮获取 servlet 信息

Java Set - 如何根据名称列表进行排序

Java:我怎样才能让一个球表现得像一个有弹性的弹跳球?

list - 如何使用Hibernate PersistentBag不遵守List equals契约(Contract)?

python - 在Python中,有没有一种方法可以使用.format表示法将列表打印到字符串中?

python - 如何配对两个列表?

java - 为什么 Java 集合不删除通用方法?

java - 在abstractmap类内部,为什么remove()不显示UnsupportedOperationException?