Java8 Supplier介面和Consumer介面原理解析
阿新 • • 發佈:2020-04-29
Supplier介面
package java.util.function; /** * Represents a supplier of results. * * <p>There is no requirement that a new or distinct result be returned each * time the supplier is invoked. * * <p>This is a <a href="package-summary.html" rel="external nofollow" rel="external nofollow" >functional interface</a> * whose functional method is {@link #get()}. * * @param <T> the type of results supplied by this supplier * * @since 1.8 */ @FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }
supplier介面只有一個抽象方法get(),通過get方法產生一個T型別例項。
例項:
package me.yanand; import java.util.function.Supplier; public class TestSupplier { public static void main(String[] args) { Supplier<Apple> appleSupplier = Apple::new; System.out.println("--------"); appleSupplier.get(); } } class Apple{ public Apple() { System.out.println("建立例項"); } }
Consumer介面
package java.util.function; import java.util.Objects; /** * Represents an operation that accepts a single input argument and returns no * result. Unlike most other functional interfaces,{@code Consumer} is expected * to operate via side-effects. * * <p>This is a <a href="package-summary.html" rel="external nofollow" rel="external nofollow" >functional interface</a> * whose functional method is {@link #accept(Object)}. * * @param <T> the type of the input to the operation * * @since 1.8 */ @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(T t)定義了要執行的具體操作;注意看andThen方法,接收Consumer<? super T>型別引數,返回一個lambda表示式,此表示式定義了新的執行過程,先執行當前Consumer例項的accept方法,再執行入參傳進來的Consumer例項的accept方法,這兩個accept方法接收都是相同的入參t。
例項:
package me.yanand; import java.util.function.Consumer; public class TestConsumer { public static void main(String[] args) { Consumer<Integer> consumer = (t) -> { System.out.println(t*3); }; Consumer<Integer> consumerAfter = (s) -> { System.out.println("之後執行:"+s); }; consumer.andThen(consumerAfter).accept(5); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。