Monday, June 10, 2013

RemDupFromList.java

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

No comments:

Post a Comment