日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java8 :: 用法 (JDK8 双冒号用法)

發布時間:2024/1/23 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java8 :: 用法 (JDK8 双冒号用法) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

代碼其實很簡單:

以前的代碼一般是如此的:

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);});} } 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} } 上面的所有方法執行玩的結果都是如下: 1 2 3 4print value : a print value : b print value : c print value : d在JDK8中,接口Iterable 8中默認實現了forEach方法,調用了 JDK8中增加的接口Consumer內的accept方法,執行傳入的方法參數。JDK源碼如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25/*** 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方法?,F在這種接口除了上面提到的,還有BiConsumer,BiFunction,BinaryOperation等,在java.util.function包下的接口,大多數都有,后綴為Supplier的接口沒有和別的少數接口。

總結

以上是生活随笔為你收集整理的java8 :: 用法 (JDK8 双冒号用法)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。