Java删除ArrayList中的重复对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20433692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:53:25  来源:igfitidea点击:

Java remove duplicate objects in ArrayList

javaarraylistduplicates

提问by eggHunter

I have a very lengthy ArrayList comprised of objects some of them however, are undoubtedly duplicates. What is the best way of finding and removing these duplicates. Note: I have written a boolean-returning compareObjects() method.

我有一个很长的 ArrayList 由对象组成,但其中一些对象无疑是重复的。查找和删除这些重复项的最佳方法是什么。注意:我编写了一个返回布尔值的 compareObjects() 方法。

回答by ashes999

You mentioned writing a compareObjectsmethod. Actually, you should override the equalsmethod to return truewhen two objects are equal.

你提到写一个compareObjects方法。实际上,当两个对象相等时,您应该覆盖该equals方法以返回true

Having said that, I would just return a new list that contains unique elements from the original:

话虽如此,我只想返回一个包含原始元素的新列表:

ArrayList<T> original = ...
List<T> uniques = new ArrayList<T>();
for (T element : original) {
  if (!uniques.contains(element)) {
    uniques.add(element);
  }
}

This only works if you override equals. See this questionfor more information.

这仅在您覆盖equals. 有关更多信息,请参阅此问题

回答by e.doroskevic

Example

例子

List<Item> result = new ArrayList<Item>();
Set<String> titles = new HashSet<String>();

for( Item item : originalList ) {
    if( titles.add( item.getTitle() ) {
        result.add( item );
    }
}

Reference

参考

Set
Java Data Structures

设置
Java 数据结构

回答by Nana Ghartey

Hashsetwill remove duplicates. Example:

Hashset将删除重复项。例子:

Set< String > uniqueItems = new HashSet< String >();
uniqueItems.add("a");
uniqueItems.add("a");
uniqueItems.add("b");
uniqueItems.add("c");

The set "uniqueItems" will contain the following : a, b, c

集合“uniqueItems”将包含以下内容:a、b、c