java8中:: 用法示例(JDK8雙冒號用法)
JDK8中有雙冒號的用法,就是把方法當做參數(shù)傳到stream內(nèi)部,使stream的每個元素都傳入到該方法里面執(zhí)行一下。
代碼其實很簡單:
以前的代碼一般是如此的:
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方法,調(diào)用了 JDK8中增加的接口Consumer內(nèi)的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ù)接口。
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關文章
Spring?循環(huán)依賴之AOP實現(xiàn)詳情
這篇文章主要介紹了Spring?循環(huán)依賴之AOP實現(xiàn)詳情,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的盆友可以參考一下2022-07-07
SpringCloud之網(wǎng)關、服務保護和分布式事務詳解
網(wǎng)關負責路由、身份驗證及用戶ID傳遞,配置管理支持熱更新與動態(tài)路由,服務保護通過限流、隔離、熔斷防止雪崩,分布式事務采用XA模式強一致性或AT模式高性能但控制復雜2025-09-09
Java編譯錯誤問題:需要class,interface或enum
這篇文章主要介紹了Java編譯錯誤問題:需要class,interface或enum,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
IDEA JeeSite框架httpSession.invalidate()無效問題解決方案
這篇文章主要介紹了IDEA JeeSite框架httpSession.invalidate()無效問題解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09

