So, I'm almost always trying to use Streams in Java.
There are only a handful of times when Streams are not a perfect fit. And most of the times, this is when there is more than one list, and you need to traverse them in sync.
So, we have different ways of doing the same thing. Let's count 'em down.
We'll use the following test setup, using the new Java Money and Currency reference implementation1 2.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This was way back when we didn't have anything better.
And let's be honest, sometimes this is all you need and it is still surprisingly readable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is one of my, let us say, less perfect attempts.
It's nice that I've used the for-each construct, but too bad I've hacked an additional index to it to do what I want.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
So, my colleague at work provided me with this solution, to get away from the whole for-loop (at least, superficially, when you look deep deep down into it, it's just a for loop written as a stream.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
I has to use a reduce in the example, because one of the disadvantages here, is that it's not allowed to reassign variables inside a lambda. Variables should be effectively final.
This disadvantage is not present in for-loops.
But I've also seen some truly horrendous hacks where people started using things like AtomicInteger as a "wrapper" workaround, so they could manipulate the inside of the wrapper inside the lambda.