snippetjavaCritical
How to convert an Array to a Set in Java
Viewed 0 times
arrayhowjavasetconvert
Problem
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:
Any ideas?
java.util.Arrays.asList(Object[] a);Any ideas?
Solution
Like this:
In Java 9+, if unmodifiable set is ok:
In Java 10+, the generic type parameter can be inferred from the arrays component type:
Be careful
Set.of throws IllegalArgumentException - if there are any duplicate
elements in someArray.
See more details: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)
If you want an unmodifiable set and you might have duplicate elements in the array, do the following:
Set mySet = new HashSet<>(Arrays.asList(someArray));In Java 9+, if unmodifiable set is ok:
Set 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: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)
If you want an unmodifiable set and you might have duplicate elements in the array, do the following:
var mySet = Set.copyOf(Arrays.asList(array));Code Snippets
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));Set<T> mySet = Set.of(someArray);var mySet = Set.of(someArray);var mySet = Set.copyOf(Arrays.asList(array));Context
Stack Overflow Q#3064423, score: 1436
Revisions (0)
No revisions yet.