Thursday 26 July 2012

How to convert ArrayList to Set in Java with Example

Converting ArrayList to Set in Java means creating a Set implementation like HashSet from an ArrayList full of objects.Before Converting your ArrayList into hashSet do remember that List keep insertion order and guarantees same but Set doesn't have such obligation. Also List allows duplicates but Set doesn't allow any duplicates, which means if you have duplicates in your ArrayList they will be lost when you convert ArrayList to HashSet and that's the reason why sometime size of ArrayList doesn't match with size of HashSet after conversion.

The complete source code is given below:


import java.util.ArrayList;
import java.util.HashSet;

public class ConvertFromArrayListToSetExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");
  arrayList.add("2");
  arrayList.add("1");

  System.out.println("Arraylist contains : ");

  for (Object e : arrayList) {

   System.out.println(e);
  }

  /**
   * Constructs a new set containing the elements in the specified
   * collection.
   **/
  HashSet numberSet = new HashSet(arrayList);

  System.out.println("HashSet contains : ");

  for (Object e : numberSet) {

   System.out.println(e);
  }

 }

}


The output is:



Arraylist contains :
1
2
3
2
1
HashSet contains :
3
2
1

No comments:

Post a Comment