mihu
mihu

Reputation: 65

Java 8 stream for each and peek

I stumbled upon a task with a stream that I couldn't solve. I had to modify the code to print abcABC instead of aAbBcC.

I understand why it's printed this way.

// prints 'a b c' then prints 'A B C'
List<String> strings = List.of("a", "b", "c");
    strings.stream()
           .peek(str -> System.out.println(str))
           .map(str -> str.toUpperCase())
           .forEach(str -> System.out.println(str));

I appreciate any help.

Upvotes: 2

Views: 907

Answers (1)

Eran
Eran

Reputation: 394146

Here's one way to do it:

List<String> strings = List.of("a", "b", "c");
    strings.stream()
           .peek(str -> System.out.println(str))
           .sorted()
           .map(str -> str.toUpperCase())
           .forEach(str -> System.out.println(str));

The sorted() operation must process all the elements of the Stream before the terminal operation can start outputting the elements (since you can't sort a Stream without going over all its elements).

Therefore, this causes peek() on all the elements to be executed before the first upper case element is outputted by forEach().

Upvotes: 3

Related Questions