Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
Alex Avatar asked Oct 28 '17 10:10

Alex


2 Answers

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.

like image 144
Yoshua Nahar Avatar answered Nov 15 '22 17:11

Yoshua Nahar


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.

like image 10
Ousmane D. Avatar answered Nov 15 '22 15:11

Ousmane D.