JDK8中有雙冒號的用法,就是把方法當做參數(shù)傳到stream內部,使stream的每個元素都傳入到該方法里面執(zhí)行一下。
創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供老河口網站建設、老河口做網站、老河口網站設計、老河口網站制作等企業(yè)網站建設、網頁設計與制作、老河口企業(yè)網站模板建站服務,10年老河口做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。
代碼其實很簡單:
以前的代碼一般是如此的:
public class AcceptMethod { public static void printValur(String str){ System.out.println("print value : "+str); } public static void main(String[] args) { List al = Arrays.asList("a","b","c","d"); for (String a: al) { AcceptMethod.printValur(a); } //下面的for each循環(huán)和上面的循環(huán)是等價的 al.forEach(x->{ AcceptMethod.printValur(x); }); } }
現(xiàn)在JDK雙冒號是:
public class MyTest { public static void printValur(String str){ System.out.println("print value : "+str); } public static void main(String[] args) { List al = Arrays.asList("a", "b", "c", "d"); al.forEach(AcceptMethod::printValur); //下面的方法和上面等價的 Consumer methodParam = AcceptMethod::printValur; //方法參數(shù) al.forEach(x -> methodParam.accept(x));//方法執(zhí)行accept } }
上面的所有方法執(zhí)行玩的結果都是如下:
print value : a
print value : b
print value : c
print value : d
在JDK8中,接口Iterable 8中默認實現(xiàn)了forEach方法,調用了 JDK8中增加的接口Consumer內的accept方法,執(zhí)行傳入的方法參數(shù)。
JDK源碼如下:
/** * 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改動的,在接口里面可以有默認實現(xiàn),就是在接口前加上default,實現(xiàn)這個接口的函數(shù)對于默認實現(xiàn)的方法可以不用再實現(xiàn)了。類似的還有static方法?,F(xiàn)在這種接口除了上面提到的,還有BiConsumer,BiFunction,BinaryOperation等,在java.util.function包下的接口,大多數(shù)都有,后綴為Supplier的接口沒有和別的少數(shù)接口。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對創(chuàng)新互聯(lián)的支持。
網頁題目:java8中::用法示例(JDK8雙冒號用法)
當前網址:http://www.rwnh.cn/article0/gjhhoo.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供品牌網站設計、定制開發(fā)、定制網站、響應式網站、域名注冊、網站策劃
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)