Java Lambda - BiFunction example








BiFunction represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.

Method

  1. BiFunction apply
  2. BiFunction andThen

Example

The following example shows how to use BiFunction.

import java.util.function.BiFunction;
/*  w  w  w. jav a 2 s.c o m*/
public class Main {
  public static void main(String[] args) {
    BiFunction<String, String,String> bi = (x, y) -> {      
      return x + y;
    };

    System.out.println(bi.apply("java2s.com", " tutorial"));
  }
}

The code above generates the following result.





Example 2

The following code shows how to use BiFunction as a parameter.

import java.util.function.BiFunction;
public class Main {
/*from  w  w  w. j a  v a  2 s  . c  o m*/
  public static void main(String[] args) {
    Calculator calculator = new Calculator();
    String result = calculator.calc((a, b) -> ": " + (a * b),3,  5);

    System.out.println(result);

  }
}

class Calculator {
  public String calc(BiFunction<Integer, Integer, String> bi, Integer i1, Integer i2) {
      return bi.apply(i1, i2);
  }
}

The code above generates the following result.





Example 3

The following code shows how to map by Function.

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class Main {
//from ww  w . j  a  va  2 s  .com
  public static void main(String[] args) {
    List<Integer> _numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    Function<Integer, Integer> lambda = value -> value * 2;
    List<Integer> doubled = _numbers.stream()
            .map(lambda)
            .collect(java.util.stream.Collectors.toList());
    
    System.out.println(doubled);
  }
}

The code above generates the following result.

Example 4

The following code shows how to create Function from method reference.

//  ww  w  . j a  v  a 2 s . co m
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class Main {

   public static void main(String[] args) {
     List<Double> numbers = Arrays.asList(1D, 25D, 100D);
     System.out.println(transformNumbers(numbers, Math::sqrt));
   }
   
   private static List<String> transformNumbers(List<Double> numbers, Function<Double, Double> fx) {
     List<String> appliedNumbers = new ArrayList<>();
     for (Double n : numbers) {
        appliedNumbers.add(String.valueOf(fx.apply(n)));
     }
     return appliedNumbers;
  }   
}

The code above generates the following result.