Saturday 14 November 2015

How to remove duplicates from ArrayList


In Java, List permits ordered access of their elements. They can have duplicates because their lookup key is the position not some hash code, every element can be modified while they remain in the list where as Set represents a collection of unique elements and while elements are in set, they must not be modified.While there is no restriction preventing you from modifying elements in a set, if an element is modified, then it could become forever lost in the set.

In this problem, to remove duplicates from an ArrayList, you can store the element of list in the Hashset . You can iterate over Hashset or you can convert the Hashset into new ArrayList.

Sample Program:-

 import java.util.ArrayList;  
 import java.util.HashSet;  
 import java.util.List;  
 import java.util.Set;  
 public class RemoveDuplicates {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           List<String> l = new ArrayList<String>();  
           l.add("A");  
           l.add("B");  
           l.add("C");  
           l.add("A");  
           System.out.println("Before removing duplicates: ");  
           for (String s : l) {  
                System.out.println(s);  
           }  
           Set<String> set = new HashSet<String>(l);  
           List<String> newlist = new ArrayList<String>(set);  
           System.out.println("after removing duplicates: ");  
           for (String s : newlist) {  
                System.out.println(s);  
           }  
      }  
 }  


Output:-

 Before removing duplicates:   
 A  
 B  
 C  
 A  
 after removing duplicates:   
 A  
 B  
 C  


Enjoy Programming.

No comments:

Post a Comment