Alex
Alex

Reputation: 2030

Java stream unexpected result

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?

Upvotes: 9

Views: 241

Answers (2)

Yoshua Nahar
Yoshua Nahar

Reputation: 1344

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.

Upvotes: 3

Ousmane D.
Ousmane D.

Reputation: 56423

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.

Upvotes: 11

Related Questions