java8 :: 用法 (JDK8 雙冒號用法)

JDK8中有雙冒號的用法,就是把方法當作參數傳到stream內部,使stream的每一個元素都傳入到該方法裏面執行一下。html

代碼其實很簡單:java

之前的代碼通常是如此的:less

public class AcceptMethod {

    public static void  printValur(String str){
        System.out.println("print value : "+str);
    }

    public static void main(String[] args) {
        List<String> al = Arrays.asList("a","b","c","d");
        for (String a: al) {
            AcceptMethod.printValur(a);
        }
      //下面的for each循環和上面的循環是等價的  
        al.forEach(x->{
            AcceptMethod.printValur(x);
        });
    }
}

  如今JDK雙冒號是:函數

public class MyTest {
    public static void  printValur(String str){
        System.out.println("print value : "+str);
    }

    public static void main(String[] args) {
        List<String> al = Arrays.asList("a", "b", "c", "d");
        al.forEach(AcceptMethod::printValur);
        //下面的方法和上面等價的
        Consumer<String> methodParam = AcceptMethod::printValur; //方法參數
        al.forEach(x -> methodParam.accept(x));//方法執行accept
    }
}

  

  上面的全部方法執行玩的結果都是以下:ui

print value : a
print value : b
print value : c
print value : d

  在JDK8中,接口Iterable 8中默認實現了forEach方法,調用了 JDK8中增長的接口Consumer內的accept方法,執行傳入的方法參數。this

JDK源碼以下:code

/**
     * Performs the given action for each element of the {@code Iterable}
     * until all elements have been processed or the action throws an
     * exception.  Unless otherwise specified by the implementing class,
     * actions are performed in the order of iteration (if an iteration order
     * is specified).  Exceptions thrown by the action are relayed to the
     * caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     for (T t : this)
     *         action.accept(t);
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if the specified action is null
     * @since 1.8
     */
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

 另外補充一下,JDK8改動的,在接口裏面能夠有默認實現,就是在接口前加上default,實現這個接口的函數對於默認實現的方法能夠不用再實現了。相似的還有static方法。如今這種接口除了上面提到的,還有BiConsumer,BiFunction,BinaryOperation等,在java.util.function包下的接口,大多數都有,後綴爲Supplier的接口沒有和別的少數接口。orm

相關文章
相關標籤/搜索