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.