Unique values in ArrayList Java

Hi All,

If you have an arrayList of string values and if you want to extract  all unique values from it.A seemingly obvious way to do this would be to create a list and before adding the next item to check that an identical item doesn’t already exist in the list.

ArrayList uuniqueList = new ArrayList();

for (Object myObj : myList)
if (!uuniqueList.contains(myObj))
uuniqueList.add(myObj);

or There is a collection in Java collection framework which we can use to add only unique values no duplicates are allowed in that.
The collection name is HashSet.

HashSet ht=new HashSet();
ht.add(“R1”);
ht.add(“R2”);
ht.add(“R1”);// now the first element value is going to be replaced with this one
System.out.println(“Output: “+ht); //Output: [R2, R1]

Thanks
R Vashi.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.