Tuesday 4 April 2017

How to avoid duplicates from List / ArrayList

Hii frnds…this is the question that I have faced many times in interview, very popular frequently asked question. Let’s see in detail.
ArrayListExample.java

package java8s;

import java.util.*;
public class ArrayListExample {

          public static void main(String[] args) {
                  
                  
                                      ArrayList al = new ArrayList();
                    
                                            al.add("First");
                                            al.add("Second");
                                            al.add("Third");
                                            al.add("First");     //Duplicate
                                            al.add("First");     //Duplicate
                    
                                          
                                              ArrayList al1 = new ArrayList(new HashSet(al));     
                    
                                           // ArrayList al2 = new ArrayList(new LinkedHashSet(al));     
                    
                                           Iterator it= al1.iterator();
                                           while(it.hasNext())
                                           {
                                                 System.out.println(it.next());
                                           }
                    
                             }
                  

          }
Output:
Second
Third
First 

No comments:

Post a Comment