天天看點

函數式接口consumer

@FunctionalInterface

1.此注解表明該接口是一個函數式接口,所謂的函數式接口,是指“有且隻有一個抽象方法”

2.接口中的靜态方法,預設方法(default修飾),以及java.lang.Object類中的方法都不算抽象方法。

3.如果接口符合函數式接口的定義,則此注解加不加無所謂,加了會友善編譯器檢查。如果不符合函數式接口定義,則此注解會報錯。

先來看下stream的函數接口

@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); };
    }
}      
//List
@Override
    public void forEach(Consumer<? super E> action) {        //函數接口
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);              //調用具體實作
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }


list.forEach(s -> System.out.println(s))      
//注解用于檢查是否是函數式接口,default、static除外,有且隻有一個抽象方法
@FunctionalInterface
public interface FunctionTest {
    void saveMessage(String message);

    default void saveMessage2(){
        System.out.println(" defaultMethod.....");
    };

    static void aaa(){
        System.out.println("static method .....");
    }
}


      
public class Test1 {
    public static void main(String[] args) {
        FunctionTest functionTest = new FunctionTest() {
            @Override
            public void saveMessage(String message) {
                System.out.println("111111");
            }
        };

        FunctionTest functionTest2 = s -> System.out.println(s);

        functionTest2.saveMessage("saveMessage........");

        Consumer<Integer> consumer = new Consumer<Integer>() {
            @Override
            public void accept(Integer o) {
                System.out.println(o);
            }
        };

        Consumer<Integer> consumer1 = s -> System.out.println(s);

        consumer1.accept(11111);

    }
}      
java.util.function jdk還提供了其他的接口供使用,很友善,可以不需要自己定義接口,也不用寫具體的impl檔案。      
上一篇: 結對作業1
下一篇: 結對作業1

繼續閱讀