Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday 27 April 2016

How to remove duplicate data from arraylist





package samset;

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

public class RemoveDuplicateData {

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

      myList.add("one");
      myList.add("two");
      myList.add("three");
      myList.add("one");//Duplicate Element
      myList.add("one");//Duplicate Element

     // java provide directly passed your arraylist data in HashSet constructor.. 
   
        HashSet set=new HashSet(myList);

     // Now you create new List and add HashSet data in List constructor

        List myList2 = new ArrayList(set); //no order

    //  If you want your List data is show in order form don't worry you use LinkedHashSet         collection
     // List myList  = new ArrayList(new LinkedHashSet(myList)); 

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

}

}

Note :-

if you want how to change Set data to ArrayList or ArrayList to Set the see 

Set setobject = new HashSet(listObject);
List listobject = new ArrayList(setObject);


Output :-

one,two,three


Enjoy friends
Thank you


No comments:

Post a Comment