Skip to content

Instantly share code, notes, and snippets.

@martijndwars
Created November 27, 2017 14:36
Show Gist options
  • Select an option

  • Save martijndwars/52f96b5f5061b0da86dc89c7bcd28657 to your computer and use it in GitHub Desktop.

Select an option

Save martijndwars/52f96b5f5061b0da86dc89c7bcd28657 to your computer and use it in GitHub Desktop.
Java 8 stream are lazy. Or not?

I've always learned that Java 8 streams are lazy. As such, I would expect that:

Optional<Integer> intOpt = Stream
  .of(1, 2, 3)
  .flatMap(i -> Stream.of(4, 5, 6))
  .filter(i -> {System.out.println(i); return true;})
  .findAny();

applies the filter only once. However, the above program outputs:

4
5
6

and the value of intOpt is an Optional[4]. If the filter performs some expensive function, then the above code will perform this expensive function more times than necessary.

Streams are not so lazy after all!

@martijndwars

martijndwars commented Nov 27, 2017

Copy link
Copy Markdown
Author

A quick Google search shows that I'm not the only one surprised by this semantics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment