通过使用 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
立即学习“Java免费学习笔记(深入)”;
使用 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)); 注意:
- 这些方法都将数组中的原始值转换为 Set 中的包装类对象(例如 Integer)。
- 如果数组包含 null 值,可能会引发
NullPointerException。











