2、集合:eachWithIndex

2023-04-29  本文已影响0人  许你一枝花

1、说明
集合的 eachWithIndex 方法 , 该函数传入一个 Closure 闭包作为参数 , 闭包中有 2 22 个参数 , 分别是 T 和 Integer 类型的 , T 就是集合元素类型 , Integer 是当前遍历的集合元素的索引值 ;
因此 , 使用 eachWithIndex 方法遍历集合 , 可以在传入的闭包中 , 得到集合的 当前遍历条目值 , 和 当前遍历的下标索引 ;
eachWithIndex 方法 返回值是 self 自身 , 可以看到 , 该方法的 返回值还是集合本身 , 如果在遍历过程中修改集合的值 , 原集合的值会被修改 ;
2、实例

class GroovyTest {

    static void main(args) {

        List<Person> persons = [new Person("张三","19"), new Person("李四","25"), new Person("王五","40")]
        List<Person> persons2 = persons.eachWithIndex{ Person entry, int i ->
            entry.userName = entry.userName+"_update"
        }
        println persons
        println persons2
    }
  }

输出:

[Person{userName='张三_update', age='19'}, Person{userName='李四_update', age='25'}, Person{userName='王五_update', age='40'}]
[Person{userName='张三_update', age='19'}, Person{userName='李四_update', age='25'}, Person{userName='王五_update', age='40'}]

上一篇 下一篇

猜你喜欢

热点阅读