gpt4 book ai didi

java - BinaryOpertor for List 添加列表

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:19:45 25 4
gpt4 key购买 nike

在上一个问题中我之前问过Which FunctionalInterface should I use?

现在我试图添加到 List<Integer>而不仅仅是两个整数ab ,这样每个索引都会添加到另一个列表的相同索引中。

我以前有过

 BinaryOperator<Integer> binaryOperator = Integer::sum;

使用 binaryOperator.apply(int a,int b) 将两个整数相加.有没有类似的方式比如

BinaryOperator<List<Integer>> binaryOperator = List<Integer>::sum;

然后在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()))....

这种逻辑的通用名称是“zip”;即,当给定两个输入序列时,它会产生一个输出序列,其中使用某个函数将输入序列中位于同一位置的每两个元素组合在一起。

标准库中没有为此内置的方法,但您可以找到一些通用实现 here .

例如,在链接帖子的已接受答案中使用 zip 方法,您可以简单地执行以下操作:

List<Integer> result = zip(f.stream(), s.stream(), (l, r) -> l + r).collect(toList());

或使用方法引用:

List<Integer> result = zip(f.stream(), s.stream(), Math::addExact).collect(toList());

其中 fs 是您的整数列表。

关于java - BinaryOpertor for List<Integer> 添加列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com