Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More then 1 command in the Java 8 foreach function

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.

like image 698
Quatsch Avatar asked Nov 28 '22 23:11

Quatsch


2 Answers

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

like image 95
Jack Avatar answered Dec 01 '22 13:12

Jack


Use this:

map.forEach(
    (k,v) -> {
        System.out.println(k);
        v.forEach(t->System.out.print(t.getDescription()))
    }
);
like image 27
Mohammed Aouf Zouag Avatar answered Dec 01 '22 14:12

Mohammed Aouf Zouag