Java remove duplicate objects in ArrayList [duplic

2019-02-13 12:18发布

This question already has an answer here:

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.

3条回答
Rolldiameter
2楼-- · 2019-02-13 12:54

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楼-- · 2019-02-13 12:57

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

查看更多
对你真心纯属浪费
4楼-- · 2019-02-13 13:10

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

查看更多
登录 后发表回答