Get unique values from arraylist in java

SDas picture SDas · Nov 17, 2012 · Viewed 232.2k times · Source

I have an ArrayList with a number of records and one column contains gas names as CO2 CH4 SO2 etc.Now i want to retrieve different gas names(unique) only without repetation from the ArrayList. How can it be done?

Answer

jahroy picture jahroy · Nov 17, 2012

You should use a Set. A Set is a Collection that contains no duplicates.

If you have a List that contains duplicates, you can get the unique entries like this:

List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());

NOTE: This HashSet constructor identifies duplicates by invoking the elements' equals() methods.