Java 8 Stream收集为ArrayList<int[]>时出现编译错误
问题解决:Java 8 Stream 收集为 List<int[]> 编译错误修复
错误原因
你代码里用的 Collectors.toList(ArrayList<int[]>::new) 是错误写法——Collectors.toList() 方法没有接受构造方法引用的重载版本,它只有无参的 toList(),无法直接指定List的实现类,这就是编译报错的根源。
修复方案
如果需要明确指定用 ArrayList<int[]> 存储结果,应该用 Collectors.toCollection() 方法,它专门用来指定集合实现类,接受集合的构造器引用作为参数。
修正后的完整代码
IntStream.iterate(0, i -> i + chunkSize) .limit((long) Math.ceil((double) input.length / chunkSize)) .mapToObj(j -> Arrays.copyOfRange(input, j, Math.min(j + chunkSize, input.length))) .collect(Collectors.toCollection(ArrayList<int[]>::new));
另外,代码里的三元表达式可以简化成 Math.min(j + chunkSize, input.length),逻辑完全一致,可读性更好。
额外说明
如果业务上不需要强制指定是 ArrayList,直接用无参的 Collectors.toList() 也可以,它会返回一个 List<int[]> 实例,只是具体实现类由JDK决定(通常也是ArrayList,但不做保证):
.collect(Collectors.toList());
内容的提问来源于stack exchange,提问作者Vibhanshu Jha
相关产品推荐
相关产品推荐

