通过使用 Arrays.asList(array) 将数组转换为 List,再通过 Set 构造函数创建 Set,或使用 Streams 的 Collectors.toSet() 方法,可以将 Java 数组转换为 Set。如果要保留重复值,可以使用 LinkedHashSet 而不是 HashSet。
如何将 Java 数组转换为 Set
直接方法
使用 Arrays.asList(array) 将数组转换为 List,然后使用 Set 的构造函数创建一个 Set:
int[] myArray = {1, 2, 3, 4, 5};
Set mySet = new HashSet<>(Arrays.asList(myArray)); 使用 Streams
使用 Streams 的 Collectors.toSet() 方法:
int[] myArray = {1, 2, 3, 4, 5};
Set mySet = Arrays.stream(myArray).boxed().collect(Collectors.toSet()); 保留重复值
要保留重复值,请使用 LinkedHashSet 而不是 HashSet:
int[] myArray = {1, 2, 2, 3, 4, 5};
Set mySet = new LinkedHashSet<>(Arrays.asList(myArray)); 注意:
NullPointerException。