More then 1 command in the Java 8 foreach function

2019-04-11 20:49发布

问题:

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.

回答1:

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).



回答2:

Use this:

map.forEach(
    (k,v) -> {
        System.out.println(k);
        v.forEach(t->System.out.print(t.getDescription()))
    }
);


回答3:

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