lambda表达式使用JDK1.8 常见的函数式接口

2019-11-25  本文已影响0人  那个名字特别特别长的家伙是我

jdk1.8 中的java.util.function类提供了大量的函数式接口,以供方便的使用lambda表达式。
本文对主要的函数式接口做一些简单的介绍。

一.Predicate<T>

Predicat 接收参数T对象,返回一个Boolean类型的对象。

Predicate.png

根据源码,我们需要实现test方法,返回类型为Boolean类型。
举例:

Predicate<String> pr = (String name) -> "true".equals(name);
System.out.println(pr.test("true"));

运行结果:

true

二.Consumer<T>

Consumer 接收参数T对象,不返回任何对象。

Consumer .png

根据源码,我们需要实现无返回值的accept方法。
举例:

Consumer<String> cu =(String test) -> System.out.println("this is Consumer demo:"+test);
cu.accept("hello consumer");

运行结果:

this is Consumer demo:hello consumer

三.Function<T,R>

Function 接收参数T对象,返回R对象。

Function.png

根据源码,我们需要实现apply方法,传参为T对象,返回值为R对象。
举例:

 Function<Integer,String > fc = (Integer num) -> "test return:"+num;
 System.out.println(fc.apply(22));

运行结果:
test return:22

四.Supplier<T>

Supplier 不接受任何参数,直接获取指定T类型返回值。


Supplier.png

根据源码,需要实现get方法。
举例:

Supplier<String> sp =()->"test Supplier";
System.out.println(sp.get());

运行结果:

test Supplier

五.UnaryOperator<T>

unaryOperator 接收参数T,通过业务逻辑处理后返回更新后的T类型参数


UnaryOperator.png

根据源码,UnaryOperator继承了Function类,根据前文描述,我们要实现Function类的apply方法。
举例:

UnaryOperator<String> uo =(String test) -> "unaryOperator update string:"+test;
System.out.println(uo.apply("test"));

运行结果:

unaryOperator update string:test

六.BiFunction<T,U,R>

Bifunction 接收第一个参数T,第二个参数U,返回R类型参数。


Bifunction .png

根据源码需要实现apply方法。
举例:

 BiFunction<String,Integer,String> bf =(String name,Integer age) -> "test BiFunction, my name is "+name+",my year's old is "+age;
 System.out.println(bf.apply("Tom", 18));

运行结果:

test BiFunction, my name is Tom,my year's old is 18

七.BinaryOperator<T>

BinaryOperator 接收两个参数T,返回更新后的T类型参数。


BinaryOperator .png

根据源码,BinaryOperator继承了Bifunction,所以我们同样实现apply方法即可。
举例:

BinaryOperator<String> bo = (String name,String sport)->"test BinaryOperator,my name is "+name+",my favourite sport is "+sport;
System.out.println(bo.apply("Tom", "basketball"));

运行结果:

test BinaryOperator,my name is Tom,my favourite sport is basketball
上一篇 下一篇

猜你喜欢

热点阅读