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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章