我想在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

其他回答

Varargs也会起作用!

Stream.of(T... values).collect(Collectors.toSet());
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

使用Guava,您可以做到:

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

在完成Arrays.asList(array)之后,可以执行Setset=newHashSet(list);

下面是一个示例方法,您可以编写:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

这是JDK6中的Collections.addAll(java.util.Collection,T…)。

另外:如果我们的数组中充满了原语呢?

对于JDK<8,我只需编写一个明显的For循环,一次完成包装和添加到set。

对于JDK>=8,一个有吸引力的选项是:

Arrays.stream(intArray).boxed().collect(Collectors.toSet());