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 (ie with a loop) but I would like something a bit neater, something like:

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

Any ideas?


Like this:

Set<T> mySet = new HashSet<T>(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);

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

用番石榴你可以做到:

T[] array = ...
Set<T> set = Sets.newHashSet(array);
链接地址: http://www.djcxy.com/p/46356.html

上一篇: CSS样式表可以是双向的吗?

下一篇: 如何将数组转换为Java中的Set