I have been wondering about this for a week or two. I don't mean limit(), which stops after a predetermined number of elements. Maybe I might want to run a Stream until one of (numeric) elements equals 0. It is easy enough to do with loops:-
1: Let's imagine that maxCount is initialised to 0x7fff_ffff_ffff_ffffL or MIN_VALUE.
2: Let's imagine you can reassign it without breaching the rules about effectively final.
3: Let's imagine I can write even worse code. That would be quite an achievement, however.
The nearest I had got to it was something like this:-Horrible, isn't it? How would you do it?
I was looking through the Stream documentation an hour or so ago wondering whether they had added a terminateIf() method and, lo and behold, found this method. It's new in Java9 Brilliant. Exactly the sort of thing I was thinking of.I actually found this method first, which appears to be the opposite of takeWhile, so I thought there was bound to be the counterpart, only if it starts with t it is at the bottom of the method summary.
So, assuming that the operation you take in the loop is some sort of aggregation, then effectively we want to implement a short-circuiting reduction on the stream. And since the problem statement allows for dirty hacks, we can have fun with code that should never see the light of day.
Imagine our aim was to calculate the product of a stream of integers:
Here we're processing three more numbers than we needed to, and would like to terminate early when we encounter that 0. Clojure actually has a pretty cool function for that called reduced that "forces" the reduction to terminate with the value supplied to that function. What if we tried something similar here with some ugly trickery?
posted 1 year ago
Thank you for the cow whoever it was.
Did anybody notice the error in my original post?
It took me a while to find this old post, but maybe it can help. It is certainly an alternative to the code shown.
Stephan did show how to implement 'takeWhile' (I couldn't find it, but maybe he can show it again).