I want to remove duplicates from a list but what I am doing is not working:
List<Customer> listCustomer = new ArrayList<Customer>();
for (Customer customer: tmpListCustomer)
{
if (!listCustomer.contains(customer))
{
listCustomer.add(customer);
}
}
IMHO best way how to do it these days:
Suppose you have a Collection "dups" and you want to create another Collection containing the same elements but with all duplicates eliminated. The following one-liner does the trick.
It works by creating a Set which, by definition, cannot contain duplicates.
Based on oracle doc.
The cleanest way is:
and override
hascode
andequals
over the Id's properties of each entityList → Set → List (distinct)
Just add all your elements to a
Set
: it does not allow it's elements to be repeated. If you need a list afterwards, use newArrayList(theSet)
constructor afterwards (wheretheSet
is your resulting set).Does Customer implement the
equals()
contract?If it doesn't implement
equals()
andhashCode()
, thenlistCustomer.contains(customer)
will check to see if the exact same instance already exists in the list (By instance I mean the exact same object--memory address, etc). If what you are looking for is to test whether or not the same Customer( perhaps it's the same customer if they have the same customer name, or customer number) is in the list already, then you would need to overrideequals()
to ensure that it checks whether or not the relevant fields(e.g. customer names) match.Note: Don't forget to override
hashCode()
if you are going to overrideequals()
! Otherwise, you might get trouble with your HashMaps and other data structures. For a good coverage of why this is and what pitfalls to avoid, consider having a look at Josh Bloch's Effective Java chapters onequals()
andhashCode()
(The link only contains iformation about why you must implementhashCode()
when you implementequals()
, but there is good coverage about how to overrideequals()
too).By the way, is there an ordering restriction on your set? If there isn't, a slightly easier way to solve this problem is use a
Set<Customer>
like so:Which will nicely remove duplicates for you, since Sets don't allow duplicates. However, this will lose any ordering that was applied to
tmpListCustomer
, sinceHashSet
has no explicit ordering (You can get around that by using aTreeSet
, but that's not exactly related to your question). This can simplify your code a little bit.Using java 8 stream api.
Output:
Before values : [one, one, two]
After Values : [one, two]