Program to demonstrate how to convert an Array into a Set in Java.
package com.hubberspot.examples; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class ArrayToSet { public static void main(String[] args) { // 1. Creating an array of duplicate integers Integer[] array = { 1,2,3,3,2,1,4,5,6,6,5,4,3,2,1,8,9,10 }; // 2. Printing the elements of array on console System.out.println("Elements in Array are : "); for(int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } // 3. Converting array of integers to List by using // java.util.Arrays static method asList(). It takes // in the object of array and returns us back with // a backed list List list = Arrays.asList(array); // 4. Creating a Set object by passing it // elements of List. Set discards duplicate values // if tried to inserted into it. Set set = new HashSet(list); // 5. Creating an Iterator object from Set // by calling iterator() method of Set Iterator iterator = set.iterator(); System.out.println(); System.out.println("Elements in Set are : "); // Looping each element in the Set using // iterator and printing the Set conatining // no duplicate values. while(iterator.hasNext()) { Object i = iterator.next(); System.out.print(i + " "); } } }Output of the program :