Java Lambda Body Statements








We can use statements such as break, continue, return, and throw inside the body of a lambda expression.

We cannot use the jump statements to do non-local jump.

Example

The following code shows how to use break statement to exit a for loop in lambda expression.

import java.util.function.Function;
/*  ww  w  .j av  a 2  s  .c om*/
public class Main {

  public static void main(String[] argv) {
    Function<String,String> func1 = y -> {
      for(int i=0;i<10;i++){
        System.out.println(i);
        if(i == 4){
          break;
        }
      }
      return y + " from java2s.com" ;
    };
    System.out.println(func1.apply("hi"));
    
  }
}

The code above generates the following result.





Example 2

We cannot use break statement in the lambda expression in order to jump out to a for loop outside lambda expression.

import java.util.function.Function;
/*from   w w  w  .  j  a  v a  2 s. c o m*/
public class Main {

  public static void main(String[] argv) {
    for(int i=0;i<10;i++){
      System.out.println(i);
      if(i == 4){

        Function<String,String> func1 = y -> {
          //break;
          return y + " from java2s.com" ;
        };
        System.out.println(func1.apply("hi"));

      }
    }
    
  }
}

The code above generates the following result.