How to remove duplicate User Defined Objects from a List collection object

Hey there!

Welcome to ClearUrDoubt.com.

In this post, we will look at a program to remove duplicates from a List.

  • Removing duplicate primitive and String values from List is a bit easy. We can use “Set” collection to remove the duplicates(if the insertion order is not important in the List).

Check out the below code:

 

  • If we need to remove duplicates from a List object where it contains User Defined Objects, the User Defined Class should override “hashCode()” and “equals()” methods of Object class.

The Set collection uses Hashtable as an underlying data structure. So if two objects return same hashCode() and equals() method returns true for them, the object will not be added to the Set collection.

Let’s create a Person class and override the hashCode() and equals() methods.

 

Now let’s look at the program to remove duplicates:

Output:

Happy learning :).

Please leave a reply in case of any queries.

One Reply to “How to remove duplicate User Defined Objects from a List collection object”

Leave a Reply

Your email address will not be published. Required fields are marked *