Java Lambdas and Streams: pass streams around

2.5k Views Asked by At

I have a fairly dumb question. We all know that stream can have a number of intermediate operations but the real computation is done only when we call some terminal operation. Is it common to pass streams around without calling terminal operation for a long time?

Let me explain what I mean. Consider the following example with Iterator/Iterable

  1. Read file with buffered reader in lines, return Iterator with next() overrided to call reader.readLine()
  2. In the upper class use guava's Iterators.transform to say lowercase everything.
  3. In the upper class wrap with another Iterator which may be split's the line from upstream iterator by coma and returning tuples of words in the line
  4. In the final class consume the iterator by iterating over it and writing to some OutputStream.

With all that I have completely lazy computation done from the start till the end. No intermediate collections are used, etc.

If I wanted to do the same with streams I guess I should pass around the Stream object itself. Is it very common to do so? Can you share some links with me?

0

There are 0 best solutions below