Java 8 Consumer、Supplier、Predicate、Function

These interfaces in java.util.functionthe package, respectively Consumer(consumer), supplier(supply type), predicate(verb type), function(functional)
below to say something about the usage of this interface from the specific application scenario.

Consumer Interface

Source:

Consumer.java

/**
 * 代表这样一种操作: 接收一个单值输入,没有返回值。与大部分函数式接口不同,
 *  Consumer一般通过"副作用"来操作。
 * Consumer 的函数式方法是accept
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * 这个默认方法与Function接口中的addThen方法类似,对于给定的入参after(类型也是Consumer),
     * 先执行上面的accept方法,再执行after中的accept方法。
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Consumer Interface example uses

     @Test
    public void test_Consumer(){
        //使用consumer接口实现方法
        System.out.println("使用consumer接口实现方法");
        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        Stream<String> stream = Stream.of("aaa", "bbb");
        stream.forEach(consumer);

        System.out.println("*********************");

        //使用lambda表达式, Stream的forEach方法需要的入参就是一个consumer接口
        System.out.println("使用lambda表达式");
        Consumer<String> consumer1 = (s) -> System.out.println(s);//lambda表达式返回的就是一个Consumer接口
        stream = Stream.of("aaa", "bbb");
        stream.forEach(consumer1);
        //更直接的方式
        //stream.forEach((s) -> System.out.println(s));
        System.out.println("********************");

        //使用方法引用,方法引用也是一个consumer
        System.out.println("使用方法引用");
        Consumer consumer2 = System.out::println;
        stream = Stream.of("aaa", "bbb");
        stream.forEach(consumer2);
        //更直接的方式
        //stream.forEach(System.out::println);
        System.out.println("********************");

        //演示Consumer的andThen方法
        Consumer<String> addHello = s -> System.out.println("hello");
        Consumer consumer3 = s -> System.out.println(s);
        //先执行consumer3定义的accept方法,再执行addHello定义的accept
        System.out.println("演示Consumer的andThen方法");
        stream = Stream.of("aaa", "bbb");
        stream.forEach(consumer3.andThen(addHello));
    }

Output:

使用consumer接口实现方法
aaa
bbb
*********************
使用lambda表达式
aaa
bbb
********************
使用方法引用
aaa
bbb
********************
演示Consumer的andThen方法
aaa
hello
bbb
hello

Guess you like

Origin www.cnblogs.com/greatLong/p/11976821.html