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.
List<Item> result = new ArrayList<Item>();
Set<String> titles = new HashSet<String>();
for( Item item : originalList ) {
if( titles.add( item.getTitle() )) {
result.add( item );
}
}
Set
Java Data Structures
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With