简体   繁体   English

Java ArrayList在自定义条件下删除重复项

[英]Java ArrayList remove duplicates on a custom condition

I have an array list of items of class 我有一个类的项目列表

Class foo {
    String name;
    String time;
}

I want to get a list of foo objects with unique names. 我想获得一个具有唯一名称的foo对象列表。 If two objects in the list have same name I want to retain only the one with least time (lexicographic is fine). 如果列表中的两个对象具有相同的名称,我想只保留一个时间最短的对象(lexicographic很好)。 This list is being returned by an underlying library so I can not do anything at insert time. 此列表由底层库返回,因此我无法在插入时执行任何操作。 I know this is easy with a map in O(n) time and space (worst case). 我知道在O(n)时间和空间(最坏的情况)中使用地图很容易。 Is there a more efficient solution ? 有更有效的解决方案吗?

What is the problem with : 有什么问题:

// myList is the List returned by the library
List<foo> new List = new ArrayList<foo>(new LinkedHashSet<foo>(myList));

Override the equals() and hashCode() in foo . 覆盖fooequals()hashCode()

This list is being returned by an underlying library so I can not do anything at insert time. 此列表由底层库返回,因此我无法在插入时执行任何操作。 I know this is easy with a map in O(n) time and space (worst case). 我知道在O(n)时间和空间(最坏的情况)中使用地图很容易。 Is there a more efficient solution ? 有更有效的解决方案吗?

I believe no , that is the most optimized solution . 我相信不,这是最优化的解决方案。 Look at this SO answer . 看看这个答案

为什么不简单地使用java.util.Set并且不要忘记覆盖foo类的equalshashCode方法。

Even if there was a way to modify the class to get a proper hash code, the question would be, which hash code should it be. 即使有一种方法来修改类以获得正确的哈希代码,问题仍然是,它应该是哪个哈希码。 Normally, hash codes and equality are using all properties of an object, so such a standard implementation would not help here as you want to have unique objects regarding a single property of the instances. 通常,哈希码和相等性使用对象的所有属性,因此这样的标准实现在这里没有帮助,因为您希望拥有关于实例的单个属性的唯一对象。

There is no standard hash map allowing you to provide a custom hash and equality function but you can do this for sorted maps. 没有标准的哈希映射允许您提供自定义哈希和相等功能,但您可以对已排序的映射执行此操作。 This will not give you O(1) like hashing, but it can give you O(log(n)) for a lookup which is still better than O(n). 这不会给你O(1)像哈希,但它可以给你O(log(n))的查找仍然比O(n)更好。

Here is how it works like: 以下是它的工作方式:

List<foo> list = // however you get it
Set<foo> set=new TreeSet<>(FooComparator.INSTANCE);
// now the set has no duplicates regarding foo.name

…

final class FooComparator implements Comparator<foo>
{
  static final FooComparator INSTANCE = new FooComparator();
  public int compare(foo o1, foo o2)
  {
    return o1.name.compareTo(o2.name);
  }
}
class foo {
  String name;
  String time;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM