The Simplest Way to Convert Arrays to Set in Java:
Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
Sample Java Program:
package com.crunchify.tutorials; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author Crunchify.com */ public class CrunchifyArraysToSet { public static void main(String[] args) { Integer[] numbers = { 7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4 }; Set<Integer> set = new HashSet<Integer>(Arrays.asList(numbers)); System.out.println("Print Set Value via toString(): " + set.toString()); //if you want to use Iterator to print value System.out.println("\nPrint Set Value via Iterator: "); for (Iterator<Integer> iterator = set.iterator(); iterator.hasNext();) { Object o = iterator.next(); System.out.print(o + " "); } } }
Other must read: How to convert HashMap to ArrayList in Java?
Output:
Print Set Value via toString(): [4, 5, 6, 7, 8, 9, 10] Print Set Value via Iterator: 4 5 6 7 8 9 10
Notice how we have used Generics also in above code snippet. Thus if you have an ArrayList
than you can convert it to Set with one simple line of code.
Hope this is useful. Other Java Tutorials.