How to debug stream().map(...) with lambda expressions?
I usually have no problem debugging lambda expressions while using Eclipse or IntelliJ IDEA. Just set a breakpoint and be sure not to inspect the whole lambda expression (inspect only the lambda body).
Another approach is to use peek
to inspect the elements of the stream:
List<Integer> naturals = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13);
naturals.stream()
.map(n -> n * 2)
.peek(System.out::println)
.collect(Collectors.toList());
UPDATE:
I think you're getting confused because map
is an intermediate operation
- in other words: it is a lazy operation which will be executed only after a terminal operation
was executed. So when you call stream.map(n -> n * 2)
the lambda body isn't being executed at the moment. You need to set a breakpoint and inspect it after a terminal operation was called (collect
, in this case).
Check Stream Operations for further explanations.
UPDATE 2:
Quoting Holger's comment:
What makes it tricky here is that the call to map and the lambda expression are in one line so a line breakpoint will stop on two completely unrelated actions.
Inserting a line break right after
map(
would allow you to set a break point for the lambda expression only. And it’s not unusual that debuggers don’t show intermediate values of areturn
statement. Changing the lambda ton -> { int result=n * 2; return result; }
would allow you to inspect result. Again, insert line breaks appropriately when stepping line by line…
IntelliJ has such a nice plugin for this case as a Java Stream Debugger plugin. You should check it out: https://plugins.jetbrains.com/plugin/9696-java-stream-debugger?platform=hootsuite
It extends the IDEA Debugger tool window by adding the Trace Current Stream Chain button, which becomes active when debugger stops inside of a chain of Stream API calls.
It has nice interface for working with separate streams operations and gives you opportunity to follow some values that u should debug.
You can launch it manually from the Debug window by clicking here: