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

Consumer可以改变入参的内部状态

//结合Consumer可以让其他对象直间接用lamaba表达式

//案例1
Student A=new Student('AA');
Consumer<Student> B=e -> Student.addName('BB');
B.accept(A);//这时A中的Name值为BB

//案例2
test(1,e->{System.out.println(e);}); public static <T> void test(Int e, Consumer<? super T> c) { c.accept(e); }

 

posted @ 2018-06-13 17:36  巴啦啦大魔王  阅读(2009)  评论(0编辑  收藏  举报