我正在尝试对 Integer 流使用 reduce 方法来获取所有值的总和。但是出现语法错误并且无法找出错误。
List<Integer> ee = new ArrayList<Integer>();
Function<? super Integer, ? extends Integer> f3 = x -> x / 2;
BinaryOperator<? extends Integer> accumulator = (x, y) -> x + y;
ee.stream().map(f3).reduce(new Integer(0), accumulator);
它给出了错误:
The method reduce(capture#2-of ? extends Integer, BinaryOperator<capture#2-of ? extends Integer>) in the type Stream<capture#2-of ? extends Integer> is not applicable for the arguments (Integer, BinaryOperator<capture#7-of ? extends Integer>)
最佳答案
问题出在你到达那里的所有界限上。虽然我需要花一些时间来弄清楚(然后解释)确切编译器认为正在发生的事情,但如果您只是更改所有内容以使用具体类型……毕竟,这并不是真正的“扩展整数的东西,但我们不确定是什么”的流。它们只是整数。这段代码编译得很好,也更容易理解。
Function<Integer, Integer> f3 = x -> x / 2;
BinaryOperator<Integer> accumulator = (x, y) -> x + y;
int result = ee.stream().map(f3).reduce(Integer.valueOf(0), accumulator);
如评论中所述,自动装箱和使用方法引用可以显着简化最后一行(并消除对 accumulator
变量的需要):
int result = ee.stream().map(f3).reduce(0, Integer::sum);
第一个片段保留了问题的更多结构,因此更容易适应其他累加器函数。
关于Java流在减少操作的情况下给出语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813716/