Lambda body statements

Description

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;
/*  w  ww  . j av  a 2s. c o m*/
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;
/*w w w.  jav  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.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial