在Java 8中, BiFunction是功能接口; 它接受两个参数并返回一个对象。
BiFunction.java
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}
- T –函数的第一个参数的类型。
- U –函数第二个参数的类型。
- R –函数结果的类型。
1. BiFunction <T,U,R>
1.1本示例使用两个Integers
并返回Integer
, Double
或List
Java8BiFunction1.java
package com.mkyong;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
public class Java8BiFunction1 {
public static void main(String[] args) {
// takes two Integers and return an Integer
BiFunction<Integer, Integer, Integer> func = (x1, x2) -> x1 + x2;
Integer result = func.apply(2, 3);
System.out.println(result); // 5
// take two Integers and return an Double
BiFunction<Integer, Integer, Double> func2 = (x1, x2) -> Math.pow(x1, x2);
Double result2 = func2.apply(2, 4);
System.out.println(result2); // 16.0
// take two Integers and return a List<Integer>
BiFunction<Integer, Integer, List<Integer>> func3 = (x1, x2) -> Arrays.asList(x1 + x2);
List<Integer> result3 = func3.apply(2, 3);
System.out.println(result3);
}
}
输出量
5
16.0
[5]
2. BiFunction <T,U,R> + Function <T,R>
2.1此BiFunction
接受两个Integer
并返回Double
,然后使用