Shankh is London based consultancy started on 2011 to provide consultancy services primarily in Java. With several successful Java projects under our belt, we started exploring mobile based services towards end of 2012 which led to our first android/ios/windows-phone app which is staged for release in 2013

Some Random quotes

Innovation distinguishes between a leader and a follower. -Steve Jobs

It is not that i am smarter than others, i just persist with problems longer

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 = 
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]


One Response to “Remove duplicates from a list in Java”

  1. Radhe Says:

    Problem with using HashSet is that you will lose the order, better use LinkedHashSet to remove duplicates from ArrayList as shown in that article.

Leave a Reply