本文翻译自:How to convert an Array to a Set in Java
I would like to convert an array to a Set in Java. 我想将数组转换为Java中的Set。 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? 有任何想法吗?
#1楼
参考:https://stackoom.com/question/CrCB/如何在Java中将数组转换为Set
#2楼
In Eclipse Collections , the following will work: 在Eclipse集合中 ,以下内容将起作用:
Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);
Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();
Note: I am a committer for Eclipse Collections 注意:我是Eclipse Collections的提交者
#3楼
Java 8: 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]
#4楼
After you do Arrays.asList(array)
you can execute Set set = new HashSet(list);
在执行Arrays.asList(array)
您可以执行Set set = new HashSet(list);
Here is a sample method, you can write: 这是一个示例方法,您可以编写:
public <T> Set<T> GetSetFromArray(T[] array) {
return new HashSet<T>(Arrays.asList(array));
}
#5楼
Like this: 像这样:
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
In Java 9+, if unmodifiable set is ok: 在Java 9+中,如果不可修改的设置是可以的:
Set<T> mySet = Set.of(someArray);
In Java 10+, the generic type parameter can be inferred from the arrays component type: 在Java 10+中,可以从数组组件类型推断泛型类型参数:
var mySet = Set.of(someArray);
#6楼
new HashSet<Object>(Arrays.asList(Object[] a));
But I think this would be more efficient: 但我认为这会更有效:
final Set s = new HashSet<Object>();
for (Object o : a) { s.add(o); }