Java 8 foreach函数中有超过1个命令
是否可以在Java 8中引入的Map.foreach函数中使用多个命令?
所以与其:
map.forEach((k, v) -> System.out.println(k + "=" + v));
我想做的事情如下:
map.forEach((k, v) -> System.out.println(k)), v.forEach(t->System.out.print(t.getDescription()));
让我们假设k是字符串而v是集合。
lambda语法允许对主体进行两种定义:
- 单个,返回值的表达式,例如:
x -> x*2
- 多个语句,用大括号括起来,例如:
x -> { x *= 2; return x; }
x -> { x *= 2; return x; }
第三个特例是允许您在调用void
返回方法时避免使用花括号的情况,例如: x -> System.out.println(x)
。
用这个:
map.forEach( (k,v) -> { System.out.println(k); v.forEach(t->System.out.print(t.getDescription())) } );
如果你有一个流你可以使用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