Java—Consumer接口

概述

Consumer接口是java.util.function包中的一部分。它用来表示带有一个参数并且生成一个结果。然而这种类型的函数却不返回任何结果。

示例

下面我们编写一个示例来说明它的用法:

假如我们有这样一个需求,有一个内部元素类型为整型的List,我们将每一个成员都乘以2,并且最后进行输出。

1、使用面向对象的编程方法

public class ObjectTest {

    public ObjectTest(){
        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(2);
        list.add(6);

        showList(towMul(list));
    }

    /**
     * 对List中的每个元素进行乘2操作
     * @param list
     * @return newList
     */
    private void towMul(List<Integer> list){
        for(int i=0;i<list.size();i++){
            list.set(i,list.get(i)*2);
        }
    }

    /**
     * 对List进行遍历
     * @param list
     */
    private void showList(List<Integer> list){
        for(Integer value : list){
            System.out.println(value);
        }
    }

    public static void main(String[] args) {
        new ObjectTest();
    }
}

2、函数式

下面我们使用函数式编程来进行实现:

public class Test {

    public Test() {
        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(2);
        list.add(6);

        //定义函数:对List中的所有元素进行乘2操作
        Consumer<List<Integer>> twoMul = value -> {
            for(int i=0;i<value.size();i++){
                value.set(i,value.get(i)*2);
            }
        };

        //定义函数:对List进行遍历
        Consumer<List<Integer>> showList = value -> value.stream().forEach(a -> {
            System.out.println(a);
        });

        //调用函数完成业务
        twoMul.andThen(showList).accept(list);
    }

    public static void main(String[] args) {
        new Test();
    }
}

通过上面的两个示例我们来总结一下Consumer接口的用法:

Consumer接口用法说明

我们先查看一下Consumer的源码实现:

@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); };
    }
}

1、accept()方法

这个方法接受一个泛型类型的值作为实参,并对其进行相关操作。并且该方法没有返回值。

2、andThen()方法

它的返回值是一个复合型的Consumer接口,括号里面的Consumer参数将在第一个Consumer执行完成后执行。在上面的调用中:twoMul.andThen(showList).accept(list),twoMul是第一个Consumer,而名为showList的Consumer是参数,会在twoMul执行完成之后执行。

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注