Java remove duplicate objects in ArrayList [duplicate]

时光毁灭记忆、已成空白 提交于 2019-11-30 19:23:06

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

ashes999

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.

Nana Ghartey

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

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