BinaryOperator<T>接口的用法示例+BiFunction

转自http://www.tpyyes.com/a/java/2017/1015/285.html

转自https://blog.csdn.net/u014331288/article/details/76319219

java Function函数中的BinaryOperator<T>接口用于执行lambda表达式并返回一个T类型的返回值,下面的BinaryOperator用法示例让你简单了解一下。

import java.util.function.BinaryOperator;
public class TestDemo {
    public static void main(String[] args) {
       BinaryOperator<Integer> add = (n1, n2) -> n1 + n2;
       //apply方法用于接收参数,并返回BinaryOperator中的Integer类型
       System.out.println(add.apply(3, 4));
    }
}

返回结果为:7

当然了,也可以用来操作字符串的lambda表达式,如下。

public class TestDemo {
    public static void main(String[] args) {
       BinaryOperator<String> addStr = (n1, n2) -> n1 +"==="+ n2;
       //apply方法用于接收参数,并返回BinaryOperator中的String类型
       System.out.println(addStr.apply("3", "4"));
    }
}

返回结果就是字符串:3==4

BinaryOperator<T>中有两个静态方法,是用于比较两个数字或字符串的大小。

//获取更小的值
static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator)
//获取更大的值
static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator)

下面用小案例来学习下这两个静态方法的使用。

minBy方法使用:

import java.util.Comparator;
import java.util.function.BinaryOperator;

public class TestDemo {
   public static void main(String[] args) {
      BinaryOperator<Integer> bi = BinaryOperator.minBy(Comparator.naturalOrder());
      System.out.println(bi.apply(2, 3));
   }
}

返回结果为:2

maxBy方法使用:

public class TestDemo {
   public static void main(String[] args) {
      BinaryOperator<Integer> bi = BinaryOperator.minBy(Comparator.naturalOrder());
      System.out.println(bi.apply(2, 3));
   }
}
————————————————————————————————————————————————————————持续精进-之BiFunction————————————————————————————————————————————————————————————————————

如果你正在浏览Java8的API,你会发现java.util.function中 Function, Supplier, Consumer, Predicate和其他函数式接口广泛用在支持lambda表达式的API中。这些接口有一个抽象方法,会被lambda表达式的定义所覆盖。

@FunctionalInterface
public interface BiFunction<T, U, R> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     */
    R apply(T t, U u);
View Code

BiFunction 接受两个参数 返回一个结果

实战: 求两个数的 四则运算

   public static Integer getSum(Integer a, Integer b, BiFunction<Integer, Integer, Integer> biFunction) {

        return biFunction.apply(a, b);
    }

    public static void main(String[] args) {

        System.out.println(getSum(1,2,(a,b)->a+b));
        System.out.println(getSum(1,2,(a,b)->a-b));
        System.out.println(getSum(1,2,(a,b)->a*b));
        System.out.println(getSum(2,2,(a,b)->a/b));

    }
View Code

转载于:https://www.cnblogs.com/lijingran/p/8672861.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值