溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java8中:: 用法示例(JDK8雙冒號用法)

發(fā)布時間:2020-08-20 00:28:16 來源:腳本之家 閱讀:179 作者:A點(diǎn)點(diǎn)圈圈A 欄目:編程語言

JDK8中有雙冒號的用法,就是把方法當(dāng)做參數(shù)傳到stream內(nèi)部,使stream的每個元素都傳入到該方法里面執(zhí)行一下。

代碼其實(shí)很簡單:

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

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)是等價(jià)的 
 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);
 //下面的方法和上面等價(jià)的
 Consumer methodParam = AcceptMethod::printValur; //方法參數(shù)
 al.forEach(x -> methodParam.accept(x));//方法執(zhí)行accept
 }
}

上面的所有方法執(zhí)行玩的結(jié)果都是如下:

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

在JDK8中,接口Iterable 8中默認(rèn)實(shí)現(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);
 }
 }

另外補(bǔ)充一下,JDK8改動的,在接口里面可以有默認(rèn)實(shí)現(xiàn),就是在接口前加上default,實(shí)現(xiàn)這個接口的函數(shù)對于默認(rèn)實(shí)現(xiàn)的方法可以不用再實(shí)現(xiàn)了。類似的還有static方法?,F(xiàn)在這種接口除了上面提到的,還有BiConsumer,BiFunction,BinaryOperation等,在java.util.function包下的接口,大多數(shù)都有,后綴為Supplier的接口沒有和別的少數(shù)接口。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI