Java Lambda - Function example








Function represents a function that accepts one argument and produces a result.

Method

  1. Function apply
  2. Function compose
  3. Function andThen
  4. Function identity




Example

The following example shows how to use Function.

import java.util.function.Function;
//  ww w  .  java  2 s .  co  m
public class Main {

  public static void main(String[] args) {
    Function<Integer,String> converter = (i)-> Integer.toString(i);
    
   
    System.out.println(converter.apply(3).length());
    System.out.println(converter.apply(30).length());
  }
}

The code above generates the following result.





Example 2

The following code shows how to pass Function as parameter.

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

  public static void main(String[] args)  {

    String result = calc((a) -> "Result: " + (a * 2), 10);

    System.out.println(result);

  }
  public static String calc(Function<Integer, String> bi, Integer i) {
    return bi.apply(i);
  }  
}

The code above generates the following result.