我想在Java中将数组转换为Set。有一些明显的方法可以做到这一点(即使用循环),但我想做一些更整洁的事情,比如:

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

有什么想法吗?


当前回答

private Map<Integer, Set<Integer>> nobreaks = new HashMap();
nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
System.out.println("expected size is 3: " +nobreaks.get(1).size());

输出为

expected size is 3: 1

将其更改为

nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));

输出为

expected size is 3: 3

其他回答

使用stanford-stagger-3.0.jar中的CollectionUtils或ArrayUtils

import static edu.stanford.nlp.util.ArrayUtils.asSet;
or 
import static edu.stanford.nlp.util.CollectionUtils.asSet;

  ...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);

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]

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

注意:我是Eclipse集合的提交人

有时使用一些标准库会有很大帮助。尝试查看Apache Commons集合。在这种情况下,您的问题简单地转化为以下内容

String[] keys = {"blah", "blahblah"}
Set<String> myEmptySet = new HashSet<String>();
CollectionUtils.addAll(pythonKeywordSet, keys);

这里是CollectionsUtils javadoc

如果需要构建一个内部只有一个元素的不可变集合,可以使用Collections.singleton(…)

Set<String> mySet = Collections.singleton("Have a good day :-)");

这并不能回答最初的问题,但可能对某人有用(至少对我来说是这样)。如果你认为这个答案不合适,告诉我,我会删除它。