我正在尝试处理 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) { ... }
不幸的是,我的解决方案没有编译,我无法理解突出显示的行的编译器错误:
The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,capture#1-of ?,Collection<Object>>)
有什么建议吗?
最佳答案
IntStream
不包含 collect
接受类型为 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()
将返回一个由该流的元素组成的 Stream,每个元素装箱为一个 Integer。
或
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.mapToObj(Integer::valueOf)
.collect(Collectors.toCollection(ArrayList::new));
关于java - 如何将整数流过滤到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994593/