Last night, I saw a post on my twitter feed titled “Why Functional Programming in Java is Dangerous” where the author tries to implement the clojure code
in a functional style in Java, then concludes that “Functional idioms in Java are performance bugs waiting to bite you” after trying to load all of the Integers Java can handle into an ArrayList.
This morning, I then saw the response post “Bad Programming in Java Is Dangerous” which shows how the required result can be achieved with a liberal use of Iterators.
I thought I’d give this a go with the groovy-stream library, and came up with the following code:
It’s only when we call the
collect method that we start generating integers from the initial stream.
Of course, you can do it a single line (though it gets a bit funky updating x)