英文:
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 <= 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-> n.getStonesInPit())
.collect(Collectors.summingInt(Integer::intValue));
int num2 = playerB.stream()
.map(n-> n.getStonesInPit())
.collect(Collectors.summingInt(Integer::intValue));
专注分享java语言的经验与见解,让所有开发者获益!
评论