Java 8 foreach函数中有超过1个命令

Cap*_*o90 3 java lambda java-8

是否可以在Java 8中引入的Map.foreach函数中使用多个命令?

所以与其:

map.forEach((k, v) -> 
System.out.println(k + "=" + v));
Run Code Online (Sandbox Code Playgroud)

我想做的事情如下:

map.forEach((k, v) -> 
System.out.println(k)), v.forEach(t->System.out.print(t.getDescription()));
Run Code Online (Sandbox Code Playgroud)

让我们假设k是字符串而v是集合.

Jac*_*ack 9

lambda语法允许两种对人体的定义:

  • 单个,值返回的表达式,例如: x -> x*2
  • 多个语句,用大括号括起来,例如: x -> { x *= 2; return x; }

第三个特例是允许您在调用void返回方法时避免使用花括号的情况,例如:x -> System.out.println(x).


Moh*_*uag 5

用这个:

map.forEach(
    (k,v) -> {
        System.out.println(k);
        v.forEach(t->System.out.print(t.getDescription()))
    }
);
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 5

如果你有一个流你可以使用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
Run Code Online (Sandbox Code Playgroud)