Java中使用Collectors.toSet()将int数组转为Set失败问题排查
代码问题分析
第一个代码的问题与修正
Arrays.stream(arr)处理int[]数组时,返回的是**IntStream(基本类型int的流)**,而Collectors.toSet()是为对象类型的Stream<T>设计的,IntStream的collect方法不支持直接传入Collector参数——这就是编译错误提示“参数列表长度不匹配”的原因。
修正方法:先通过boxed()方法将IntStream中的int装箱为Integer,转换成Stream<Integer>,再使用Collectors.toSet()收集:
int[] arr = {2,5,2,4,6,6,1,5,4}; Set<Integer> orederSet = new HashSet<>(Arrays.stream(arr).boxed().collect(Collectors.toSet()));
如果不需要显式嵌套HashSet,可以更简洁:
Set<Integer> orederSet = Arrays.stream(arr).boxed().collect(Collectors.toSet());
(Collectors.toSet()默认返回的就是HashSet)
第二个代码的问题与修正
Arrays.asList(arr)处理int[]时,不会拆分数组中的每个int元素,而是将整个int[]数组作为单个元素,返回的是List<int[]>类型,而非List<Integer>。因此无法直接传入HashSet<Integer>的构造器(构造器要求参数为Collection<? extends Integer>)。
修正方案有两种:
- 把数组类型改为
Integer[]:
Integer[] arr = {2,5,2,4,6,6,1,5,4}; Set<Integer> orederSet = new HashSet<>(Arrays.asList(arr));
- 保留
int[],通过流转换后再收集:
int[] arr = {2,5,2,4,6,6,1,5,4}; Set<Integer> orederSet = new HashSet<>(Arrays.stream(arr).boxed().collect(Collectors.toList()));
内容的提问来源于stack exchange,提问作者user63898
相关产品推荐
相关产品推荐

