Java remove duplicate objects in ArrayList [duplicate]

独自空忆成欢 提交于 2019-12-30 06:19:12

问题


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.


回答1:


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




回答2:


You mentioned writing a compareObjects method. Actually, you should override the equals method to return true when two objects are equal.

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 question for more information.




回答3:


Hashset will remove duplicates. Example:

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



来源:https://stackoverflow.com/questions/20433692/java-remove-duplicate-objects-in-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!