java8consumer_JDK8 函数式编程之Consumer接口

源码如下

@FunctionalInterface

public interface Consumer {

/**

* Performs this operation on the given argument.

*

* @param t the input argument

*/

void accept(T t);

/**

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

* operation followed by the {@code after} 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 {@code after} operation will not be performed.

*

* @param after the operation to perform after this operation

* @return a composed {@code Consumer} that performs in sequence this

* operation followed by the {@code after} operation

* @throws NullPointerException if {@code after} is null

*/

default Consumer andThen(Consumer super T> after) {

Objects.requireNonNull(after);

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

}

}

这个接口就是接收一个泛型,然后有一个没有返回值的函数。类似的我们可以有一下使用。

import java.util.function.Consumer;

public class Main {

public static void main(String[] args) {

testConsumer();

testAndThen();

}

public static void testConsumer(){

Consumer consumer = integer -> System.out.println("print square =" +integer * integer);

consumer.accept(3);

}

public static void testAndThen(){

Consumer consumer1 = integer -> System.out.println("first =" + integer);

Consumer consumer2 = integer -> System.out.println("second =" + integer);

Consumer consumer3 = x -> {

throw new NullPointerException("test Exception");};

consumer1.andThen(consumer2).andThen(consumer3).accept(2);

}

}

输出结果如下:

print square =9

first =2

second =2

Exception in thread "main" java.lang.NullPointerException: test Exception

at Main.lambda$testAndThen$3(Main.java:17)

at java.util.function.Consumer.lambda$andThen$0(Consumer.java:65)

at Main.testAndThen(Main.java:19)

at Main.main(Main.java:7)

Process finished with exit code 1

假如把

consumer1.andThen(consumer2).andThen(consumer3).accept(2);

换成

consumer1.andThen(consumer2.andThen(consumer3)).accept(2);

输出结果会变成

print square =9

Exception in thread "main" java.lang.NullPointerException: test Exception

first =2

at Main.lambda$testAndThen$3(Main.java:17)

second =2

at java.util.function.Consumer.lambda$andThen$0(Consumer.java:65)

at java.util.function.Consumer.lambda$andThen$0(Consumer.java:65)

at Main.testAndThen(Main.java:19)

at Main.main(Main.java:7)

Process finished with exit code 1

因为方法的调用会使得consumer3的accept先调用,所以先把异常抛出了。

最后对Consuerm这个接口自己的总结。总的来说,只要比较了解lambda表达式还是比较好理解这个接口的意思的。

理解源码

default Consumer andThen(Consumer super T> after) {

Objects.requireNonNull(after);

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

}

其意思就是返回一个,同时具有当前类跟输入参数的accept方法,如同方法名字一样andThen,类似一种相加的功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值