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

本文介绍了Java中的BinaryOperator接口,通过示例展示了如何使用它进行数值和字符串的操作,包括加法和比较功能。同时,还探讨了BiFunction接口,解释了其接受两个参数并返回结果的特性,并提供了四则运算的实战应用。
摘要由CSDN通过智能技术生成

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

import java.util.function.BinaryOperator;

public class TestDemo {

public static void main(String[] args) {

BinaryOperator 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 addStr = (n1, n2) -> n1 +"==="+ n2;

//apply方法用于接收参数,并返回BinaryOperator中的String类型

System.out.println(addStr.apply("3", "4"));

}

}

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

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

//获取更小的值

static  BinaryOperator minBy(Comparator super T> comparator)

//获取更大的值

static  BinaryOperator 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 bi = BinaryOperator.minBy(Comparator.naturalOrder());

System.out.println(bi.apply(2, 3));

}

}

返回结果为:2

maxBy方法使用:

public class TestDemo {

public static void main(String[] args) {

BinaryOperator 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表达式的定义所覆盖。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

@FunctionalInterfacepublic interface BiFunction{/**

* 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 接受两个参数 返回一个结果

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public static Integer getSum(Integer a, Integer b, BiFunctionbiFunction) {returnbiFunction.apply(a, b);

}public static voidmain(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值