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.
You mentioned writing a
compareObjects
method. Actually, you should override theequals
method to returntrue
when two objects are equal.Having said that, I would just return a new list that contains unique elements from the original:
This only works if you override
equals
. See this question for more information.Example
Reference
Set
Java Data Structures
Hashset
will remove duplicates. Example:The set "uniqueItems" will contain the following : a, b, c