首页 > 解决方案 > 使用 Java 流同时在两个列表中添加数字

问题描述

我正在学习java中的流,我很困惑。我在谷歌上搜索了很多,但找不到方法。地图仍然让我感到困惑。

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

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));

标签: javalistjava-stream

解决方案


推荐阅读