日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【Groovy】集合遍历 ( 使用集合的 collect 循环遍历集合并根据指定闭包规则生成新集合 | 代码示例 )

發布時間:2025/6/17 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Groovy】集合遍历 ( 使用集合的 collect 循环遍历集合并根据指定闭包规则生成新集合 | 代码示例 ) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 一、使用集合的 collect 循環遍歷集合并根據指定閉包規則生成新集合
  • 二、代碼示例





一、使用集合的 collect 循環遍歷集合并根據指定閉包規則生成新集合



調用集合的 collect 方法進行遍歷 , 與 調用 each 方法進行遍歷 , 實現的功能是不同的 ;

collect 方法主要是 根據 一定的轉換規則 , 將 現有的 集合 , 轉換為一個新的集合 ;

新集合是 重新創建的集合 , 與原集合無關 ;


分析集合的 collect 方法 , 其傳入的的參數是一個閉包 transform , 這是 新生成集合的規則 ;

在該函數中調用了 collect 重載函數 collect(self, new ArrayList<T>(self.size()), transform) , 傳入了新的 ArrayList 集合作為參數 , 該 新的 ArrayList 集合是新創建的集合 , 其大小等于被遍歷的集合 ;

/*** 使用<code>transform</code>閉包遍歷此集合,將每個條目轉換為新值* 返回已轉換值的列表。* <pre class="groovyTestCase">assert [2,4,6] == [1,2,3].collect { it * 2 }</pre>** @param self 一個集合* @param transform 用于轉換集合中每個項的閉包* @return 轉換值的列表* @since 1.0*/public static <S,T> List<T> collect(Collection<S> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> transform) {return (List<T>) collect(self, new ArrayList<T>(self.size()), transform);}

重載的 collect 方法中 , 為新創建的集合賦值 , 根據 transform 閉包邏輯原集合的值 , 計算 新集合中對應位置元素的值 ;

/*** 方法遍歷此集合,將每個值轉換為新值 <code>transform</code> 閉包* 并將其添加到所提供的 <code>collector</code> 中.* <pre class="groovyTestCase">assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }</pre>** @param self 一個集合* @param collector 將轉換值添加到其中的集合* @param transform 用于轉換集合中的每一項的閉包* @return 將所有轉換后的值添加到其上的收集器* @since 1.0*/public static <T,E> Collection<T> collect(Collection<E> self, Collection<T> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends T> transform) {for (Object item : self) {collector.add(transform.call(item));if (transform.getDirective() == Closure.DONE) {break;}}return collector;}



二、代碼示例



代碼示例 :

class Test {static void main(args) {// 為 ArrayList 設置初始值def list = ["1", "2", "3"]// I. 使用 collate 遍歷集合 , 返回一個新集合 , 集合的元素可以在閉包中計算得來def list3 = list.collect{// 字符串乘法就是將元素進行疊加it * 2}// 打印 [1, 2, 3]println list// 打印 [11, 22, 33]println list3} }

執行結果 :

[1, 2, 3] [11, 22, 33]

總結

以上是生活随笔為你收集整理的【Groovy】集合遍历 ( 使用集合的 collect 循环遍历集合并根据指定闭包规则生成新集合 | 代码示例 )的全部內容,希望文章能夠幫你解決所遇到的問題。

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