If you wanted to log values in a stream you’d probably want to have something like the following:
Stream.of("a", "b")
.tap(?)
...
There’s no built-int tap
though, so you try:
Stream.of("a", "b")
.map(s -> {LOGGER.debug(s); return s;})
...
Yikes. Not all is lost though. You can just add your own tap:
public static <T> Function<T, T> tap(Consumer<T> consumer) {
return t -> {
consumer.accept(t);
return t;
};
}
So now you can just:
Stream.of("a", "b")
.map(tap(LOGGER::debug))
...
As a side benefit, you can likewise tap your Optional
s too:
Optional.of("a")
.map(tap(LOGGER::debug))
...