BinaryOperator 二元操作符, 传入的两个参数的类型和返回类型相同, 继承BiFunction
BinaryOperator<T>:两个T作为输入,返回一个T作为输出,对于“reduce”操作很有用
BinaryOperator<String> bina = (x, y) -> x + " " + y; BinaryOperator<Integer> reduce = (x, y) -> x - y; BinaryOperator<Double> div = (x, y) -> { if (y == 0){ System.out.println("除数不能为0"); } return x / y; } ; System.out.println(bina.apply("hello ", "world")); // hello world System.out.println(reduce.apply(10, 2)); // 8 System.out.println(div.apply(10.2, 0.0)); // Infinity
源码查看
@FunctionalInterface public interface BinaryOperator<T> extends BiFunction<T,T,T> { /** * Returns a {@link BinaryOperator} which returns the lesser of two elements * according to the specified {@code Comparator}. * * @param <T> the type of the input arguments of the comparator * @param comparator a {@code Comparator} for comparing the two values * @return a {@code BinaryOperator} which returns the lesser of its operands, * according to the supplied {@code Comparator} * @throws NullPointerException if the argument is null */ public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator); return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; } /** * Returns a {@link BinaryOperator} which returns the greater of two elements * according to the specified {@code Comparator}. * * @param <T> the type of the input arguments of the comparator * @param comparator a {@code Comparator} for comparing the two values * @return a {@code BinaryOperator} which returns the greater of its operands, * according to the supplied {@code Comparator} * @throws NullPointerException if the argument is null */ public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator); return (a, b) -> comparator.compare(a, b) >= 0 ? a : b; } }
相关阅读:Java函数式编程之UnaryOperator 一元操作符
未经允许请勿转载:程序喵 » Java函数式编程之BinaryOperator 二元操作符