Remove Duplicates in list


  • We have to create a list of String.
  • Then pass that string top Hashset.(i.e)HashSet will not allow duplicates.
  • So the resultant list is a unique list.
  • The same procedure you have to follow for Interger etc.For user definied list we have to override 
  • hashCode and Equals method.That you can see in my next post.

  1. package com.utilitySample;
  2.  import org.apache.commons.lang.StringUtils;

  3.  public class RemoveDuplicate {
  4.  public static void main(String[] args) {
  5.      List<String> arrayList1 = new ArrayList<String>();
  6.    arrayList1.add("vel");
  7.    arrayList1.add("vel");
  8.    arrayList1.add("dinesh");
  9.    arrayList1.add("dinesh");
  10.    arrayList1.add("dinesh");
  11.    arrayList1.add("prasanth");

  12.    List<String> arrayList2 = new ArrayList<String>(new HashSet<String>(arrayList1));

  13.    for (String item : arrayList2){
  14.        System.out.println(item);
  15.    }      
  16.     }
  17.  }

 Output :
  dinesh
  vel
  prasanth

3 comments:

  1. Replace the line 14 with the below code

    arrayList1 = new ArrayList(new HashSet(arrayList1));

    ReplyDelete
  2. What if i am storing an user defined object in the list? How will you remove the duplicate objects from the list?

    A quick reply would be appreciated.

    ReplyDelete
    Replies
    1. see this post http://thecodemechanic.blogspot.in/2013/07/remove-duplicate-in-userdefinied-list.html

      Delete