Is it possible to use more than one command in the Map.foreach function that got introduced with Java 8?
So instead:
map.forEach((k, v) ->
System.out.println(k + "=" + v));
I want to do something like:
map.forEach((k, v) ->
System.out.println(k)), v.forEach(t->System.out.print(t.getDescription()));
Lets pretend that k are Strings and v are Sets.
The lambda syntax allows two kinds of definitions for the body:
- a single, value-returning, expression, eg:
x -> x*2
- multiple statements, enclosed in curly braces, eg:
x -> { x *= 2; return x; }
A third special case is the one that allows you to avoid using curly braces, when invoking a void
returning method, eg: x -> System.out.println(x)
.
Use this:
map.forEach(
(k,v) -> {
System.out.println(k);
v.forEach(t->System.out.print(t.getDescription()))
}
);
If you have a stream you can use peek().
map.entrySet().stream()
.peek(System.out::println) // print the entry
.flatMap(e -> e.getValue().stream())
.map(t -> t.getDescription())
.forEach(System.out::println); // print all the descriptions