Java8函数式编程之四: 常见的函数式接口及实例

上一篇博客中Java8函数式编程之三:函数式接口 - 简书 留下的问题是关于Consumer接口的,本篇博客就来介绍一下Java8提供的重要的函数式接口。

1.Consumer接口:

我们首先看一下Consumer接口的Javadoc,比任何资料都正规的解释。

'

/**

* Represents an operation that accepts a single input argument and returns no

* result. Unlike most other functional interfaces, {@codeConsumer} is expected

* to operate via side-effects.

*/

@FunctionalInterface

public interfaceConsumer {

/**

* Performs this operation on the given argument. 通过给定的参数执行操作

*/

voidaccept(Tt);

/**

* Returns a composed {@codeConsumer} that performs, in sequence, this

* operation followed by the {@codeafter} operation. If performing either

* operation throws an exception, it is relayed to the caller of the

* composed operation.  If performing this operation throws an exception,

* the {@codeafter} operation will not be performed.

*/

defaultConsumer andThen(Consumer after) {

Objects.requireNonNull(after);

return(Tt) -> { accept(t);after.accept(t); };

}

}

'

Consumer接口中定义了一个accept()的抽象方法,它接收泛型T的对象,没有返回(void).

一句话解释就是:接收一个输入参数,不返回结果。

——————————————————————————————————

2.Function接口 :

/**

* Represents a function that accepts one argument and produces a result.

*/

@FunctionalInterface

public interfaceFunction {

/**

* Applies this function to the given argument.

*/

Rapply(Tt);

/**

* Returns a composed function that first applies the {@codebefore}

* function to its input, and then applies this function to the result.

* If evaluation of either function throws an exception, it is relayed to

* the caller of the composed function.

*/

default Function compose(Function before) {

Objects.requireNonNull(before);

return(Vv) -> apply(before.apply(v));

}

/**

* Returns a composed function that first applies this function to

* its input, and then applies the {@codeafter} function to the result.

* If evaluation of either function throws an exception, it is relayed to

* the caller of the composed function.

*/

default Function andThen(Function after) {

Objects.requireNonNull(after);

return(Tt) ->after.apply(apply(t));

}

/**

* Returns a function that always returns its input argument.

*

*@paramthe type of the input and output objects to the function

*@returna function that always returns its input argument

*/

static Function identity() {

returnt -> t;

}

}

Function接口定义了一个apply()方法,它接收一个泛型T的对象,并返回一个R对象。

一句话解释就是:输入一个参数,返回一个结果。

——————————————————

Function接口实例:

public classFunctionTest {

public static voidmain(String[] args) {

FunctionTest test =newFunctionTest();

//现在相当于传递了一个行为/动作给compute

System.out.print(test.compute(2, value -> {

return2* value;

}));

System.out.print(test.compute(5, value -> {

returnvalue +7;

}));

}

//一个计算函数

public intcompute(inta, Function function) {

returnfunction.apply(a);

}

}

————————————————————————————————————

3.BiFunction函数式接口:

/**

* Represents a function that accepts two arguments and produces a result.

* This is the two-arity specialization of {@linkFunction}.

*

*

This is afunctional interface

* whose functional method is {@link#apply(Object, Object)}.

*/

@FunctionalInterface

public interfaceBiFunction {

/**

* Applies this function to the given arguments.

*/

Rapply(Tt,Uu);

/**

* Returns a composed function that first applies this function to

* its input, and then applies the {@codeafter} function to the result.

* If evaluation of either function throws an exception, it is relayed to

* the caller of the composed function.

*/

default BiFunction andThen(Function after) {

Objects.requireNonNull(after);

return(Tt,Uu) ->after.apply(apply(t, u));

}

}

一句话总结就是:接收两个参数,得到一个结果。

——————

Bifunction实例:

public classBiFunctionTest {

public static voidmain(String[] atgs) {

BiFunctionTest test =newBiFunctionTest();

System.out.print(test.compute(1,3, (value1, value2) -> value1 + value2));

System.out.print(test.compute(1,3, (value1, value2) -> value1 - value2));

//

System.out.print(test.compute2(3,2, (value1, value2) -> value1 + value2, value -> value - value));

}

public intcompute(inta,intb, BiFunction biFunction) {

returnbiFunction.apply(a, b);

}

//使用andThen

public intcompute2(inta,intb, BiFunction biFunction, Function function) {

returnbiFunction.andThen(function).apply(a, b);

}

}

————————————————————————

4.Predicate函数式接口:

/**

* Represents a predicate (boolean-valued function) of one argument.

*

*

This is afunctional interface

* whose functional method is {@link#test(Object)}.

*

*@paramthe type of the input to the predicate

*

*@since1.8

*/

@FunctionalInterface

public interfacePredicate {

/**

* Evaluates this predicate on the given argument.

*/

booleantest(Tt);

/**

* Returns a composed predicate that represents a short-circuiting logical

* AND of this predicate and another.  When evaluating the composed

* predicate, if this predicate is {@codefalse}, then the {@codeother}

* predicate is not evaluated.

*/

defaultPredicate and(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) &&other.test(t);

}

/**

* Returns a predicate that represents the logical negation of this

* predicate.

*/

defaultPredicate negate() {

return(t) -> !test(t);

}

/**

* Returns a composed predicate that represents a short-circuiting logical

* OR of this predicate and another.  When evaluating the composed

* predicate, if this predicate is {@codetrue}, then the {@codeother}

* predicate is not evaluated.

*/

defaultPredicate or(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) ||other.test(t);

}

/**

* Returns a predicate that tests if two arguments are equal according

* to {@linkObjects#equals(Object, Object)}.

*/

static Predicate isEqual(Object targetRef) {

return(null== targetRef)

? Objects::isNull

: object ->targetRef.equals(object);

}

}

一句话解释就是:接收一个参数,返回一个布尔值。

Predicate接口里的其他方法:

1.逻辑与

defaultPredicate and(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) &&other.test(t);

}

2.逻辑非 (取反)

defaultPredicate negate() {

return(t) -> !test(t);

}

3.逻辑或

defaultPredicate or(Predicate other) {

Objects.requireNonNull(other);

return(t) -> test(t) ||other.test(t);

}

4.静态方法,相等性/

static Predicate isEqual(Object targetRef) {

return(null== targetRef)

? Objects::isNull

: object ->targetRef.equals(object);

}

——————————

实例1:

public classPredicateTest {

public static voidmain(String[] args) {

List list = Arrays.asList(1,2,3,4,5,6,7,8,9);

PredicateTest test =newPredicateTest();

//找到集合中所有的奇数

test.conditionFilter(list, item -> item %2!=0);

//大于5的数

test.conditionFilter(list, item -> item >5);

//打印所有的元素

test.conditionFilter(list, item ->true);

//测试与

test.conditionFilter2(list, item -> item >5, item -> item %2==0);

//测试或

test.conditionFilter3(list, item -> item >5, item -> item %2==0);

//测试非

test.conditionFilter4(list, item -> item >5, item -> item %2==0);

//相等性判断

System.out.print(test.isEqual("test").test("test"));

}

//函数式编程提供了一种更高层次的抽象

public voidconditionFilter(List list, Predicate predicate) {

for(Integer integer : list) {

if(predicate.test(integer)) {

System.out.print(integer +" ");

}

}

}

//与

public voidconditionFilter2(List list, Predicate predicate1, Predicate predicate2) {

for(Integer integer : list) {

if(predicate1.and(predicate2).test(integer)) {

System.out.print(integer);

}

}

}

//或

public voidconditionFilter3(List list, Predicate predicate1, Predicate predicate2) {

for(Integer integer : list) {

if(predicate1.or(predicate2).test(integer)) {

System.out.print(integer);

}

}

}

//非

public voidconditionFilter4(List list, Predicate predicate1, Predicate predicate2) {

for(Integer integer : list) {

if(predicate1.and(predicate2).negate().test(integer)) {

System.out.print(integer);

}

}

}

//想等性判断

publicPredicate isEqual(Object object) {

returnPredicate.isEqual(object);

}

}

————————————————

5.Supplier函数式接口:

/**

* Represents a supplier of results.

*

*

There is no requirement that a new or distinct result be returned each

* time the supplier is invoked.

*

*

This is afunctional interface

* whose functional method is {@link#get()}.

*/

@FunctionalInterface

public interfaceSupplier {

/**

* Gets a result.

*/

Tget();

}

一句话解释就是:不接收任何参数,返回一个结果。

——————————————————————————


public classSupplierTest {

public static voidmain(String[] args){

//不接收参数,返回一个结果

Supplier supplier = () ->"hello world";

System.out.print(supplier.get());

}

}

————————————

实例2:

public classStudent {

privateStringname="zhangsan";

private intage;

publicStudent(){

}

publicStudent(String name,intage){

this.name= name;

this.age= age;

}

publicString getName() {

returnname;

}

public voidsetName(String name) {

this.name= name;

}

public intgetAge() {

returnage;

}

public voidsetAge(intage) {

this.age= age;

}

}

——————————————

public classStudentTest {

public static voidmain(String[] args){

Supplier supplier = () ->newStudent();

System.out.print(supplier.get().getName());

//使用构造方法引用

Supplier supplier1 = Student::new;

System.out.print(supplier1.get().getName());

}

}

————————————————

6.BinaryOperator函数式接口

/**

* Represents an operation upon two operands of the same type, producing a result

* of the same type as the operands.  This is a specialization of

* {@linkBiFunction} for the case where the operands and the result are all of

* the same type.

*

*

This is afunctional interface

* whose functional method is {@link#apply(Object, Object)}.

*/

@FunctionalInterface

public interfaceBinaryOperatorextendsBiFunction {

/**

* Returns a {@linkBinaryOperator} which returns the lesser of two elements

* according to the specified {@codeComparator}.

*/

public static BinaryOperator minBy(Comparator comparator) {

Objects.requireNonNull(comparator);

return(a, b) ->comparator.compare(a, b) <=0? a : b;

}

/**

* Returns a {@linkBinaryOperator} which returns the greater of two elements

* according to the specified {@codeComparator}.

*/

public static BinaryOperator maxBy(Comparator comparator) {

Objects.requireNonNull(comparator);

return(a, b) ->comparator.compare(a, b) >=0? a : b;

}

}

一句话解释就是:接收两个相同类型的参数,返回一个结果。

————————————————

public classBinaryOperatorTest {

public static voidmain(String[] args){

BinaryOperatorTest test =newBinaryOperatorTest();

System.out.print(test.compute(1,2,(a,b) -> a +b));

}

public intcompute(inta,intb, BinaryOperator binaryOperator){

returnbinaryOperator.apply(a,b);

}

publicString getShort(String a, String b, Comparator comparator){

returnBinaryOperator.minBy(comparator).apply(a,b);

}

}

——————————————————————

6.Optinal函数式接口:

/**

* A container object which may or may not contain a non-null value.

* If a value is present, {@codeisPresent()} will return {@codetrue} and

* {@codeget()} will return the value.

*

*

Additional methods that depend on the presence or absence of a contained

* value are provided, such as {@link#orElse(java.lang.Object) orElse()}

* (return a default value if value not present) and

* {@link#ifPresent(java.util.function.Consumer) ifPresent()} (execute a block

* of code if the value is present).

*/

public final classOptional

一句话解释就是:为了解决Java中的NPE问题(NullPointerExeception)

(程序员认为某个对象不会为空,而去使用这个对象调用某个方法,导致出现NullPointerExeception)

————————————————

Optinal是一个容器对象,里面可以包含或者不包含一个非空值。如果这个值存在,isPresent()方法会返回true,get()方法会返回这个值。

——————

几个工厂方法构造对象

1.构造一个值为null的对象

public static Optional empty() {

@SuppressWarnings("unchecked")

Optional t = (Optional)EMPTY;

returnt;

}

2.构造一个不为null的对象

public static Optional of(Tvalue) {

return newOptional<>(value);

}

3.构造出可能为null,也可能不为null的对象

public static Optional ofNullable(Tvalue) {

returnvalue ==null?empty() :of(value);

}

————————————————————

4.取值get();

publicTget() {

if(value==null) {

throw newNoSuchElementException("No value present");

}

returnvalue;

}

5.判断对象是否存在 isPresent()

public booleanisPresent() {

returnvalue!=null;

}

——————————————

public classOptionalTest {

public static voidmain(String[] args){

//不能new,需要用工厂方法创建

Optional optional = Optional.of("hello");

optional.ifPresent(item -> System.out.print(item));

//如果里面没有值,就打出word

System.out.print(optional.orElse("world"));

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • “您好,我们新店开业,只需耽误您几分钟,请您进店看看,我们有小礼品相送。”小F低头看看手表,离朋友约定的时间还有一...
    妞妞飞阅读 333评论 0 1
  • 没错,这是一篇蹭热的文章…… 人之初,性本善。也正因如此,人们的评判总是站在道德的至高点,比如说到出轨,比如谈到婚...
    雨歇梦微凉阅读 120评论 0 0
  • 今天是正月十二,第四天。 可乐出国的第四天。在所有人都还在回味越来越没有年味的新年时,她一个人,拖着行李,去了马来...
    蜡笔并不新阅读 258评论 0 0
  • 最近正在给果果读绘本故事,虽然他现在还听不懂,但是已经从一开始的不在意,到现在,自己能够拿着读过的绘本书翻来翻去,...
    尽力了吗阅读 486评论 0 0
  • 和游总聊天,不是一家人不进一家门啊。很多思想竟然会碰撞到一起。平时不沟通竟然也可以想到一起去。。。这就是能量场效应...
    Yao_3019阅读 160评论 0 0