Saturday, January 26, 2019

collections - 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, something like:



java.util.Arrays.asList(Object[] a);


Any ideas?


Answer



Like this:



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);


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...