我正在尝试处理一个流,Integers
并将与谓词匹配的整数(通过compare()
函数)收集到一个列表中。这是我编写的代码的粗略概述。
private List<Integer> process() {
Z z = f(-1);
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.collect(Collectors.toCollection(ArrayList::new)); // Error on this line
}
private boolean compare(Z z1, Z z2) { ... }
private Z f(int i) { ... }
不幸的是,我的解决方案无法编译,我无法理解突出显示行的编译器错误:
IntStream类型的方法collect(Supplier <R>,ObjIntConsumer <R>,BiConsumer <R,R>)不适用于参数(Collector <Object,capture#1-of?,Collection <Object >>)
有什么建议?
IntStream
不包含collect
接受type单个参数的方法Collector
。Stream
做。因此,您必须将转换IntStream
为Stream
。
您可以将装箱IntStream
到Stream<Integer>
或使用mapToObj
来实现相同的效果。
例如:
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
boxed()
将返回一个包含此流元素的流,每个元素都装在一个整数中。
要么
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.mapToObj(Integer::valueOf)
.collect(Collectors.toCollection(ArrayList::new));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句