0

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));
Jaime S
  • 1,488
  • 1
  • 16
  • 31
Shrads
  • 883
  • 19
  • 39
  • [Not easily](https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip), you're way better off with a loop. – Kayaman Apr 08 '20 at 20:34
  • Even with a loop, you would still be adding to playerA and playerB at two different moments, not simultaneously. To get the effect of simultaneous updating, you need to protect the resources with locks and such – something that databases are built to do in a transaction. – Basil Bourque Apr 08 '20 at 21:07
  • https://stackoverflow.com/questions/41661931/using-streams-instead-of-for-loop-in-java-8 – Jaybird Apr 08 '20 at 21:19

0 Answers0