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);
}
}
java 8 update
you can use stream of array as below:
I suspect you might not have
Customer.equals()
implemented properly (or at all).List.contains()
usesequals()
to verify whether any of its elements is identical to the object passed as parameter. However, the default implementation ofequals
tests for physical identity, not value identity. So if you have not overwritten it inCustomer
, it will return false for two distinct Customer objects having identical state.Here are the nitty-gritty details of how to implement
equals
(andhashCode
, which is its pair - you must practically always implement both if you need to implement either of them). Since you haven't shown us the Customer class, it is difficult to give more concrete advice.As others have noted, you are better off using a Set rather than doing the job by hand, but even for that, you still need to implement those methods.
The correct answer for Java is use a Set. If you already have a
List<Customer>
and want to de duplicate itOtherise just use a
Set
implemenationHashSet
,TreeSet
directly and skip theList
construction phase.You will need to override
hashCode()
andequals()
on your domain classes that are put in theSet
as well to make sure that the behavior you want actually what you get.equals()
can be as simple as comparing unique ids of the objects to as complex as comparing every field.hashCode()
can be as simple as returning thehashCode()
of the unique id'String
representation or thehashCode()
.