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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

【Groovy】集合遍历 ( 使用集合的 eachWithIndex 方法进行遍历 | 代码示例 )

發布時間:2025/6/17 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Groovy】集合遍历 ( 使用集合的 eachWithIndex 方法进行遍历 | 代码示例 ) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 一、使用集合的 eachWithIndex 方法進行遍歷
  • 二、代碼示例





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



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

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

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


集合 eachWithIndex 方法原型 :

/*** 迭代 iterable 類型,* 將每個項和項的索引(從零開始的計數器)傳遞給給定的閉包。** @param self 一個 Iterable 實例對象* @param closure 在每個項中執行的閉包* @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 設置初始值def list = ["1", "2", "3"]// I. 使用 eachWithIndex 遍歷集合 , 返回集合本身def list3 = list.eachWithIndex{ String entry, int i ->// String entry 是集合元素本身// int i 是集合元素下標println "$i : $entry"}println listprintln list3} }

執行結果 :

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

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的【Groovy】集合遍历 ( 使用集合的 eachWithIndex 方法进行遍历 | 代码示例 )的全部內容,希望文章能夠幫你解決所遇到的問題。

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