Friday 27 July 2012

Convert Array to HashSet in Java


This Java Example shows how to convert an array to Java HashSet object using Arrays.asList method.


import java.util.*;

public class ArrayToSetExample {

 public static void main(String[] args) {

  Integer[] numbers = { 7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4 };

  /**
   * To convert an array into a Set, first we convert it into a List using
   * Arrays.asList method. Next we create a HashSet and pass the list as
   * an argument to the constructor.
   **/

  List< integer > list = Arrays.asList(numbers);

  Set< integer > set = new HashSet< integer >(list);

  // Display elements of the set

  System.out.println("The set contains...");

  for (Integer n : set) {

   System.out.println(n);
  }
 }
}


The output is:



The set contains...
4
5
6
7
8
9
10

No comments:

Post a Comment