Retrieving unique items from a List in Java

Here is a very simple and efficient way to retrieve unique items from a java.util.List.

All you need to do is put all the items in the java.util.List into a java.util.Set and then create a new java.util.Listfrom the Set. Since a Set does not allow duplicate entries, the new List created would only have the unique items.

Below is an example:
//the initial List
ArrayList list = new ArrayList();
list.add("ID_1");
list.add("ID_2");
list.add("ID_3);
list.add("ID_2); //duplicate entry - needs to be removed
//convert the List into a Set
Set set = new HashSet(list);
//create a new List from the Set
ArrayList uniqueList = new ArrayList(set);

Note that the order of the items in the unique list will not be the same as those in the original.
To maintain the order of the initial items use a java.util.LinkedHashSet instead of a java.util.HashSet.
To sort the items in the java.util.List use a java.util.TreeSet instead.

For further details, have a look here.

Advertisements
This entry was posted in Java and tagged , , . Bookmark the permalink.

One Response to Retrieving unique items from a List in Java

  1. Bhushan says:

    Thank you. It was really helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s