java 8 Consumer 接口

java 8 Consumer 接口

java 8中开始支持函数式编程,初接触后很不适应,因为和对象的思想相差太多。在某次项目中学习了scala之后再返回来看java 8中的函数,有种似曾相识的感觉。java也在和其他语言的竞争中不断更新自己。先来看源码:

@FunctionalInterface
public interface Consumer<T> {

    /**
     * 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<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

只有两个方法,accept()  和 andThen(); consumer接受单值,没有返回值,对传入的值做操作,或者做判断业务。consumer是lambda表达式的类型。

public class ConsumerTest {

    @Test
    public void testAccept(){
        // 判断值
        Consumer<Integer> first = x -> {
            if(x % 2 == 0){
                System.out.println("偶数");
            } else {
                System.out.println("奇数");
            }
        };
        first.accept(3);
    }

    @Test
    public void testAndThen(){
        // andThen操作,先consumer1再执行consumer2,源码中的after参数
        Consumer<Integer> consumer1 = x -> System.out.println(x + x);
        Consumer<Integer> consumer2 = x -> System.out.println(x * x);
        consumer1.andThen(consumer2).accept(3);
    }

}

网上介绍的文章很多,上面只是简单的做了一个例子操作。有一个例子还可以的,写在后面

https://www.cnblogs.com/greatLong/p/11976821.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值