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);
}
}
If the code in your question doesn’t work, you probably have not implemented
equals(Object)on theCustomerclass appropriately.Presumably there is some key (let us call it
customerId) that uniquely identifies a customer; e.g.An appropriate definition of
equals(Object)would look like this:For completeness, you should also implement
hashCodeso that twoCustomerobjects that are equal will return the same hash value. A matchinghashCodefor the above definition ofequalswould be:It is also worth noting that this is not an efficient way to remove duplicates if the list is large. (For a list with N customers, you will need to perform
N*(N-1)/2comparisons in the worst case; i.e. when there are no duplicates.) For a more efficient solution you could use aHashSetto do the duplicate checking. Another option would be to use aLinkedHashSetas explained in Tom Hawtin’s answer.