Man*_*ani 3 java java-8 java-stream functional-interface
在前面的问题中,我曾问过我应该使用哪个FunctionalInterface?
现在,我尝试添加到List<Integer>而不是两个Integers a和b,这样每个索引都添加到另一个列表的相同索引中。
我以前有
BinaryOperator<Integer> binaryOperator = Integer::sum;
Run Code Online (Sandbox Code Playgroud)
用于使用加上两个整数binaryOperator.apply(int a,int b)。有没有类似的方式
BinaryOperator<List<Integer>> binaryOperator = List<Integer>::sum;
Run Code Online (Sandbox Code Playgroud)
然后得到结果List<Integer> cList?
如果要对对应索引处的元素(在此特定情况下为求和)执行一些计算,则无需使用BinaryOperator,而是使用IntStream.range来生成索引:
// generates numbers from 0 until list.size exclusive
IntStream.range(0, list.size())....
// generates numbers from 0 until the minimum of the two lists exclusive if needed
IntStream.range(0, Math.min(list.size(), list2.size()))....
Run Code Online (Sandbox Code Playgroud)
这种逻辑的通用名称是“ zip”。也就是说,当给定两个输入序列时,它会产生一个输出序列,其中使用某种功能将输入序列中位于相同位置的每两个元素组合在一起。
标准库中没有为此的内置方法,但是您可以在此处找到一些通用实现。
例如,使用zip链接帖子的可接受答案中的方法,您可以简单地执行以下操作:
List<Integer> result = zip(f.stream(), s.stream(), (l, r) -> l + r).collect(toList());
Run Code Online (Sandbox Code Playgroud)
或使用方法参考:
List<Integer> result = zip(f.stream(), s.stream(), Math::addExact).collect(toList());
Run Code Online (Sandbox Code Playgroud)
其中f和s是您的整数列表。