Pages

Tuesday, 10 September 2013

How to Remove Duplicate Values From Java List/ArrayList?



This is the question asked in our forum by some of our friend, even i faced this little issue once in my project :-)Some times we may not have chance to choose our own collection property.  For example in Hibernate HQL we used to get the output through List object, what if you get some duplicate records in our List ? not only in Hibernate, you might saw in regular usage of List as well.
So we will see how to remove duplicate objects from List or ArrayList collection.
RemDupFromList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package java4s;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

public class RemDupFromList {

    public static void main(String[] args)
    {
        List li = new ArrayList();

              li.add("one");
              li.add("two");
              li.add("three");
              li.add("one");//Duplicate
              li.add("one");//Duplicate

             // We have facility to pass a List into Set constructor and vice verse to cast      

                List li2 = new ArrayList(new HashSet(li)); //no order

             // List li2 = new ArrayList(new LinkedHashSet(li)); //If you need to preserve the order use 'LinkedHashSet'

             Iterator it= li2.iterator();
             while(it.hasNext())
             {
                 System.out.println(it.next());
             }

    }
}
Explanation
  • Take your normal List object
  • Pass that List li object to Set [Line number 22]  => So finally we have Set object in our hand, just pass this current Set object as argument to ArrayList, so we got new List object li2 without duplicate
  • But if you would like to preserve the order of data use LinkedHashSet rather HashSet
Output
one
two
three

Thing is……
Set setObject = new HashSet(listObject);
List listObject = new ArrayList(setObject);
Hope you got it :-)

No comments:

Post a Comment