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

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

有什么想法吗?


当前回答

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

其他回答

在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集合的提交人

快速:您可以做到:

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

并反转

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

对于任何解决Android问题的人:

Kotlin集合解决方案

星号*是排列运算符。它单独应用集合中的所有元素,每个元素按顺序传递给vararg方法参数。相当于:

val myArray = arrayOf("data", "foo")
val mySet = setOf(*myArray)

// Equivalent to
val mySet = setOf("data", "foo")

// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*myArray, "bar", *myArray)

不传递参数setOf()将导致空集。

除了setOf之外,您还可以对特定的哈希类型使用以下任何一种:

hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()

这是如何显式定义集合项类型的。

setOf<String>()
hashSetOf<MyClass>()

已经有很多很好的答案了,但大多数答案都不适用于基元数组(如int[]、long[]、char[]、byte[]等)

在Java 8及更高版本中,您可以使用以下命令对阵列进行装箱:

Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);

然后使用流转换为集合:

Stream.of(boxedArr).collect(Collectors.toSet());

使用Guava,您可以做到:

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