Logging inside Java Stream
Software engineer with 6+ years of experience.
Have been spending 5+ years in the fintech & payment products domain.
Specialized in backend and have delivered production-grade web app projects as well.
Background
Once upon a time, I wanted to log something that was executed inside the Java stream for debugging purposes.
But, I didn't see anything logged there.
Solution
Put the log inside the peek() method instead of map().
Example
Previously, I was logging in this way (which didn't work),
Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e))
.collect(Collectors.toList());
Stream.of("one", "two", "three", "four")
.map(val -> {
System.out.println("Value length: " + val.length();
return val;
})
.filter(val -> val.length() > 3)
.collect(Collectors.toList());
To make it works, I moved the logging to peek() ,
Stream.of("one", "two", "three", "four")
.peek(val -> System.out.println("Value length: " + val.length()))
.filter(val -> val.length() > 3)
.collect(Collectors.toList());