Remove duplicates from a list in Java
There is a simple way to remove duplicates from Lists, use HashSet or LinkedHashSet. HashSet will not preserve the ordering while LinkedHashSet will preserve it. Here is the sample code
List<String> listWithDuplicates =
Arrays.asList("to","be","or","not","to","be","that","is","the","question");
List<String> listWithoutDuplicates =
new ArrayList<String>(new LinkedHashSet<String>(listWithDuplicates));
List<String> listWithoutDuplicatesWithoutOrdering =
new ArrayList<String>(new HashSet<String>(listWithDuplicates));
Here is the output
List with duplicates:[to, be, or, not, to, be, that, is, the, question]
List with out duplicates:[to, be, or, not, that, is, the, question]
List with out duplicates without ordering:[not, to, that, is, or, question, the, be]

Leave a Reply