【JDK 8-函数式编程】4.2 BiFunction

一、BiFunction

二、改造上节课:四则运算


一、BiFunction

  • Function 只能接收一个参数要传递两个参数,则用 BiFunction

  • 两个参数:可以是两种不同数据类型

  • 调用方法:   R apply(T t, U u);

import java.util.Objects;

/**
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <R> the type of the result of the function
 */
@FunctionalInterface
public interface BiFunction<T, U, R> {

    R apply(T t, U u);

}

二、改造上节课:四则运算

import lombok.extern.slf4j.Slf4j;

import java.util.function.BiFunction;

@Slf4j
public class BiFunc {
    public static void main(String[] args) {
        int a = 20;
        Float b = 5.0f;
        log.info("{} + {} = {}", a, b, operation(a, b, (x, y) -> x + y));
        //log.info("{} + {} = {}", a, b, operation(a, b, Float::sum));
        log.info("{} - {} = {}", a, b, operation(a, b, (x, y) -> x - y));
        log.info("{} X {} = {}", a, b, operation(a, b, (x, y) -> x * y));
        log.info("{} / {} = {}", a, b, operation(a, b, (x, y) -> x / y));
    }

    public static Float operation(Integer x, Float y, BiFunction<Integer, Float, Float> of) {
        return of.apply(x, y);
    }
}

运行结果

猜你喜欢

转载自blog.csdn.net/ladymorgana/article/details/132979079