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

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

有什么想法吗?


当前回答

Java 8

我们也可以选择使用Stream。我们可以通过各种方式获取流:

Set<String> set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
System.out.println(set);

String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);

// if you need HashSet then use below option.
Set<String> strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet2);

Collectors.toSet()的源代码显示元素是一个接一个添加到HashSet中的,但规范并不保证它是HashSet。

“对类型、可变性、可序列化性或返回Set的线程安全性。"

所以最好使用后面的选项。输出为:[A、B、C、D][A、B、C、D][A、B、C、D]

不可变集(Java 9)

Java9引入了Set.of静态工厂方法,它为提供的元素或数组返回不可变的集合。

@SafeVarargs
static <E> Set<E> of​(E... elements)

有关详细信息,请检查不可变设置静态工厂方法。

不可变集(Java 10)

我们还可以通过两种方式获得不可变集合:

Set.copyOf(Arrays.asList(array))Arrays.stream(array).collector(Collectors.toUnmodifiebleList());

Collectors.toUnmodifiebleList()方法在内部使用了Java9中引入的Set.of。还要查看我的答案以了解更多信息。

其他回答

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

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

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

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

在Java 10中:

String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));

Set.copyOf返回包含给定集合元素的不可修改集合。

给定的集合不能为null,并且不能包含任何null元素。

Java 8

我们也可以选择使用Stream。我们可以通过各种方式获取流:

Set<String> set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
System.out.println(set);

String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);

// if you need HashSet then use below option.
Set<String> strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet2);

Collectors.toSet()的源代码显示元素是一个接一个添加到HashSet中的,但规范并不保证它是HashSet。

“对类型、可变性、可序列化性或返回Set的线程安全性。"

所以最好使用后面的选项。输出为:[A、B、C、D][A、B、C、D][A、B、C、D]

不可变集(Java 9)

Java9引入了Set.of静态工厂方法,它为提供的元素或数组返回不可变的集合。

@SafeVarargs
static <E> Set<E> of​(E... elements)

有关详细信息,请检查不可变设置静态工厂方法。

不可变集(Java 10)

我们还可以通过两种方式获得不可变集合:

Set.copyOf(Arrays.asList(array))Arrays.stream(array).collector(Collectors.toUnmodifiebleList());

Collectors.toUnmodifiebleList()方法在内部使用了Java9中引入的Set.of。还要查看我的答案以了解更多信息。