How to Convert an Array to a Set in Java
I Would Like to Convert an Array to a Set in Java. There Are Some Obvious Ways of Doing This (I. E. with a Loop) but I Would Like Something a Bit Neater...
I would like to convert an array to a Set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:
java.util.Arrays.asList(Object[] a);
Any ideas?
19 Answers
Like this:
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
In Java 9+, if unmodifiable set is ok:
Set<T> mySet = Set.of(someArray);
In Java 10+, the generic type parameter can be inferred from the arrays component type:
var mySet = Set.of(someArray);
Be careful
Set.of throws IllegalArgumentException - if there are any duplicate elements in someArray. See more details: (E...)
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);
That's Collections.addAll(java.util.Collection, T...) from JDK 6.
Additionally: what if our array is full of primitives?
For JDK < 8, I would just write the obvious for loop to do the wrap and add-to-set in one pass.
For JDK >= 8, an attractive option is something like:
Arrays.stream(intArray).boxed().collect(Collectors.toSet());
With Guava you can do:
T[] array = ...
Set<T> set = Sets.newHashSet(array);
Java 8:
String[] strArray = {"eins", "zwei", "drei", "vier"};
Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]
Varargs will work too!
Stream.of(T... values).collect(Collectors.toSet());
Must Read
Java 8
We have the option of using Stream as well. We can get stream in various ways:
Set<String> set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
System.out.println(set);
String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);
// if you need HashSet then use below option.
Set<String> strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet2);
The source code of Collectors.toSet() shows that elements are added one by one to a HashSet but specification does not guarantee it will be a HashSet.
"There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned."
So it is better to use the later option. The output is:
[A, B, C, D]
[A, B, C, D]
[A, B, C, D]