Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

I would like to convert an array to a Set in Java. There are some simple 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 thoughts?

1 Answer

0 votes
by (46k points)

For Java 8 and below you can try this syntax:

Set<T> mySet = new HashSet<>(Arrays.asList(someArray));

In Java 9+, if the 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);

Or with Guava you can use:

T[] array = ...

Set<T> set = Sets.newHashSet(array);

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...