【问题标题】:Finding all latest records with same id in java collections在 java 集合中查找所有具有相同 id 的最新记录
【发布时间】:2013-11-05 08:55:56
【问题描述】:
class Obj{
    int x;
    int y;
    Date z;

    public int compareTo(Obj other) {
        if(this.z.getTime() > other.getZ().getTime())
            return 1;
        else if(this.z.getTime() < other.getZ().getTime())
            return -1;
        else 
            return 0;
    }

    boolean equals(Obj other) {
        if(x== other.x && y == other.y) 
            return true; 
        else 
            return false;
    }
}

现在我有一个list&lt;Obj&gt;,我必须删除重复项,并且只有在有多个具有相同 ID 的对象时才选择最新的(最新的 z)。

sortedSet = new TreeSet(objList);
reversedSortedList = new ArrayList(sortedSet); //This will not be needed if we reverse the comparator logic. However it is not good. 
uniqueSet = new HashSet(reverseSortedList);
return uniqueSet;

这是一种很好的做事方式吗?或者有一种更清洁、更好的做事方式。对我来说,列表中的元素数量也在 1000-10000 之间

谢谢

【问题讨论】:

    标签: java list set unique treeset


    【解决方案1】:

    您可以编写一个单独的 Comparator 来比较您的对象,该对象将能够反向排序(与您实现的逻辑相反)而不是在我们的对象中实现 compareTo 方法(虽然我可以看到您的类没有实现 Comparable 接口)。

    这样你就可以直接得到反向排序的集合,你可以随时轻松更改逻辑,或者可以在不同的地方使用许多不同的比较器。

    对于 1000-10000,使用 TreeSet 是 Compartors 的不错选择。

    【讨论】:

      【解决方案2】:

      您的比较器可以优化为:

      public int compareTo(Obj other) {
              return (int)(this.z.getTime() - other.getZ().getTime());
      }
      

      【讨论】:

      • int compareTo 会出现编译错误,因为z.getTime() 返回一个long
      • 您可以显式转换为 int
      猜你喜欢
      • 2021-08-30
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 2012-03-29
      • 1970-01-01
      相关资源
      最近更新 更多