Tuesday, 25 November 2014

JAVA : How to remove duplicate values from ArrayList?

Standard
We all know that ArrayList allows duplicate elements, So how can we remove these duplicate elements if we want ? we don't have any pre defined methods to satisfy our requirement. So by passing the list to set we can achieve this.Why because set does not allows us to pass duplicates.After passing the list to set , again we will pass  set to list so, that we will get newly modified list without duplicates.
Let's go for Examples:-
in this examples i will use two classes HashSet and  LinkedHashSet the difference b/w them is if we useHashSet doesn't maintain insertion order where as  LinkedHashSet maintains insertion order like ArrayList so mostly we will use LinkedHashSet




we will see both of them in following examples.

Example:-


  1. package com.system;  
  2.    
  3.  import java.util.*;;  
  4.    
  5.  public class Test{  
  6.     
  7.   public static void main(String args[]){  
  8.      
  9.    List al=new ArrayList();  
  10.    al.add("one");  
  11.    al.add("one");  
  12.    al.add("two");  
  13.    al.add("three");  
  14.    al.add("four");  
  15.    al.add("two");  
  16.    System.out.println("Before removing The duplicates"+al);  
  17.      
  18.     //By using HashSet  
  19.      Set set=   new HashSet(al);  
  20.        
  21.      List al1=new ArrayList(set);  
  22.      System.out.println("Elements, after removing the duplicates"+al1);  
  23.        
  24.    List al2=new ArrayList();  
  25.      
  26.    al2.add("java");  
  27.    al2.add("java");  
  28.    al2.add("oracle");  
  29.    al2.add(".net");  
  30.    al2.add("SAP");  
  31.    al2.add("oracle");  
  32.    System.out.println("Before removing The duplicates"+al2);  
  33.    // By using LinkedHasSet  
  34.    Set set2=   new HashSet(al2);  
  35.    List al3=new ArrayList(set2);  
  36.    System.out.println("Elements, after removing the duplicates"+al3);  
  37.        
  38.   }  
  39.  }  

Output:-


0 comments:

Post a Comment