使用Java流同时对两个列表中的数字进行相加

huangapple 未分类评论44阅读模式
英文:

Adding numbers in two lists simultaneously using Java streams

问题

以下是已翻译的内容:

我正在学习 Java 中的流(Streams),但感到困惑。我在谷歌上搜索了很多,但没有找到合适的方法。Map 仍然让我感到困惑。

所以,我有两个相同大小为 8 的整数列表 PlayerA[]PlayerB[]。我试图将每个列表中除了最后一个元素以外的所有元素相加。

int smallPitStonesPlayerA = 0;
int smallPitStonesPlayerB = 0;
for (int i = 1; i <= 6; i++) { 			
    smallPitStonesPlayerA = smallPitStonesPlayerA + playerA.getStonesInPit(i);			
    smallPitStonesPlayerB = smallPitStonesPlayerB + playerB.getStonesInPit(i) ;
}

我迄今为止尝试过的方法。但这等效于两个循环。是否有一种方法可以只做一次这个操作?

int num1 = playerA.stream()
           .map(n -> n.getStonesInPit())
           .collect(Collectors.summingInt(Integer::intValue));

int num2 = playerB.stream()
           .map(n -> n.getStonesInPit())
           .collect(Collectors.summingInt(Integer::intValue));
英文:

I am learning streams in java and I am confused. I have search a lot on google but could not find an approach. Map still confuses me.

So, I have two integer lists PlayerA[] and PlayerB[] of same size 8. I am trying to add all elements except the last one in each list.

int smallPitStonesPlayerA = 0;
int smallPitStonesPlayerB = 0;
for (int i = 1; i &lt;= 6; i++) { 			
    smallPitStonesPlayerA = smallPitStonesPlayerA + playerA.getStonesInPit(i);			
    smallPitStonesPlayerB = smallPitStonesPlayerB + playerB.getStonesInPit(i) ;
  }

What I have tried so far. But this is equivalent to two loops. Is there a way to this once?

int num1 = playerA.stream()
           .map(n-&gt; n.getStonesInPit())
           .collect(Collectors.summingInt(Integer::intValue));

int num2 = playerB.stream()
           .map(n-&gt; n.getStonesInPit())
           .collect(Collectors.summingInt(Integer::intValue));

huangapple
  • 本文由 发表于 2020年4月9日 04:29:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/61109480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定