日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

【Groovy】集合遍歷 ( 使用集合的 eachWithIndex 方法進行遍歷 | 代碼示例 )

作者:韓曙亮 更新時間: 2021-12-12 編程語言





一、使用集合的 eachWithIndex 方法進行遍歷



集合的 eachWithIndex 方法 , 該函數(shù)傳入一個 Closure 閉包作為參數(shù) , 閉包中有 2 2 2 個參數(shù) , 分別是 T 和 Integer 類型的 , T 就是集合元素類型 , Integer 是當前遍歷的集合元素的索引值 ;

因此 , 使用 eachWithIndex 方法遍歷集合 , 可以在傳入的閉包中 , 得到集合的 當前遍歷條目值 , 和 當前遍歷的下標索引 ;

eachWithIndex 方法 返回值是 self 自身 , 可以看到 , 該方法的 返回值還是集合本身 , 如果在遍歷過程中修改集合的值 , 原集合的值會被修改 ;


集合 eachWithIndex 方法原型 :


    /**
     * 迭代 iterable 類型,
     * 將每個項和項的索引(從零開始的計數(shù)器)傳遞給給定的閉包。
     *
     * @param self    一個 Iterable 實例對象
     * @param closure 在每個項中執(zhí)行的閉包
     * @return Iterable 實例對象本身
     * @since 2.3.0
     */
    public static <T> Iterable<T> eachWithIndex(Iterable<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
        eachWithIndex(self.iterator(), closure);
        return self;
    }




二、代碼示例



代碼示例 :

class Test {
    static void main(args) {

        // 為 ArrayList 設(shè)置初始值
        def list = ["1", "2", "3"]


        // I. 使用 eachWithIndex 遍歷集合 , 返回集合本身


        def list3 = list.eachWithIndex{ String entry, int i ->
            // String entry 是集合元素本身
            // int i 是集合元素下標
            println "$i : $entry"

        }
        println list
        println list3

    }
}

執(zhí)行結(jié)果 :

0 : 1
1 : 2
2 : 3
[1, 2, 3]
[1, 2, 3]

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/shulianghan/article/details/122118919

欄目分類
最近更新