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

相关文章
相关标签/搜索