9

I have following code:

Stream.of("Java", "Stream", "Test")
      .peek(s -> System.out.print(s + " "))
      .allMatch(s -> s.startsWith("J"));

Why does it print me Java Stream?

Naman
  • 27,789
  • 26
  • 218
  • 353
Alex
  • 1,940
  • 2
  • 18
  • 36
  • 1
    See also [In Java streams is peek really only for debugging?](https://stackoverflow.com/a/33636377/2711488) – Holger Oct 28 '17 at 17:57
  • Contrary to popular way of thinking (and actual implementation) it's better to think of streams as if the last operation was pulling elements rather than the stream was pushing them. – Dariusz Oct 31 '17 at 06:05

2 Answers2

11

allMatch is short-circuiting operation as most of the streams operations are. since allMatch returned early that's why peek is only printing the first two elements.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
3

Because allMatch() checks if everyone element in the stream is true. And since the second was false, it doesn't have to check further.

So peek() won't print the 3rd element.

Yoshua Nahar
  • 1,304
  • 11
  • 28
  • Yeap, I understood that it wasn't executed for each element and that was my question - why? So you say that it stopped executing on second element and that's why I see only two values? – Alex Oct 28 '17 at 10:48
  • Yes. Because the second element for `allMatch()` was false, the stream terminates. – Yoshua Nahar Oct 28 '17 at 10:54