Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java remove duplicate objects in ArrayList [duplicate]

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.

like image 416
eggHunter Avatar asked Dec 06 '13 21:12

eggHunter


3 Answers

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

like image 68
e.doroskevic Avatar answered Nov 07 '22 13:11

e.doroskevic


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.

like image 22
ashes999 Avatar answered Nov 07 '22 14:11

ashes999


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

like image 41
Nana Ghartey Avatar answered Nov 07 '22 15:11

Nana Ghartey