Java Lambda Expression type infer

Introduction

The following code shows a lambda expression that takes a parameter.

// Another functional interface. 
interface NumericTest { 
 boolean test(int n);  
} 
 
public class Main { 
  public static void main(String args[]) 
  { //from   ww  w.  ja v  a 2 s  . c  om
    // A lambda expression that tests if a number is even. 
    NumericTest isEven = (n) -> (n % 2)==0; 
 
    if(isEven.test(10)) System.out.println("10 is even"); 
    if(!isEven.test(9)) System.out.println("9 is not even"); 
 
    // Now, use a lambda expression that tests if a number 
    // is non-negative. 
    NumericTest isNonNeg = (n) -> n >= 0; 
 
    if(isNonNeg.test(1)) System.out.println("1 is non-negative"); 
    if(!isNonNeg.test(-1)) System.out.println("-1 is negative"); 
  } 
}

It is shown again here:

(n) -> (n % 2)==0 

The type of n is not specified.

Its type is inferred from the context.

This is a valid way to write the preceding:

(int n) -> (n % 2)==0 

Here, n is explicitly specified as int.

When a lambda expression has one parameter, we do not need to surround the parameter name with parentheses.

For example, we can write the lambda expression used in the program:

n -> (n % 2)==0 

Demonstrate a lambda expression that takes two parameters.

interface My { /* w  w w  .ja v a2s  . com*/
  boolean test(int n, int d); 
} 
 
public class Main { 
  public static void main(String args[]) 
  { 

    My isFactor = (n, d) -> (n % d) == 0; 
 
    if(isFactor.test(10, 2)) 
      System.out.println("2 is a factor of 10"); 
 
    if(!isFactor.test(10, 3)) 
      System.out.println("3 is not a factor of 10");   
  } 
}

If you explicitly declare the type of a parameter, all of the parameters must have declared types.

For example, this is legal: 
(int n, int d) -> (n % d) == 0 

But this is not:

(int n, d) -> (n % d) == 0 



PreviousNext

Related