java8 - 內置函數式接口(Consumer)

Consumer

若是須要訪問類型T的對象,並對其執行某些操做,就可使用這個Consumer接口。ui

輸出list的內容
public static void main(String[] args) {
    List<String> list = Arrays.asList("1", "2", "3", "11", "22", "33");
    Consumer<String> consumer = (String str) -> System.out.println(str);
    Consumer<String> andThenConsumer = (String str) -> System.out.println("andThen:" + str);
    Consumer<String> andThen2Consumer = (String str) -> System.out.println("andThen2:" + str);
    forEach(list, consumer);
    forEach(list, consumer, andThenConsumer);
    forEach(list, consumer, andThenConsumer, andThen2Consumer);
}

public static <T> void forEach(List<T> list, Consumer<T> consumer) {
    for (T t : list) {
        consumer.accept(t);
    }
}

運行結果以下:
image.png
accept方法負責對字符串的輸出。spa

複合

andThen

除了對字符串的直接輸出,還要在前面加個andThen
public static <T> void forEach(List<T> list, Consumer<T> consumer, Consumer<T> andThenConsumer) {
    for (T t : list) {
        consumer.andThen(andThenConsumer).accept(t);
    }
}

運行結果以下:
image.png
源碼以下:3d

default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
}

因此先執行accept的方法,再執行andThen的方法。code

多個andThen

除了對字符串的直接輸出,還要在前面加個andThen以及andThen2
public static <T> void forEach(List<T> list, Consumer<T> consumer, Consumer<T> andThenConsumer, Consumer<T> andThen2Consumer) {
    for (T t : list) {
        consumer.andThen(andThenConsumer).andThen(andThen2Consumer).accept(t);
    }
}

運行結果以下:
image.png
能夠看出,accept方法先執行,而後在從左到右依次執行andThen對象

相關文章
相關標籤/搜索