首页 > 解决方案 > 在 Groovy 中将列表转换为枚举列表

问题描述

我有一个这种类型的字符串列表:

list = ['AB-000 Some text', 'AB-003 Some other text', 'AB-004 Some more text']

我怎样才能枚举这个列表(使用 Groovy),即得到以下内容:

list = ['1. AB-000 Some text', '2. AB-003 Some other text', '3. AB-004 Some more text']

标签: javaarraylistgroovy

解决方案


你可以这样做:

list.withIndex().collect{ it, index -> "${index + 1}. ${it}" }

更新:(https://gist.github.com/michalbcz/2757630提供)

或者您可以花哨并实际定义collectWithIndex方法:

List.metaClass.collectWithIndex = { yield ->
    def collected = []
    delegate.eachWithIndex { listItem, index ->
        collected << yield(listItem, index)
    }

    return collected 
}

result = list.collectWithIndex { it, index -> "${index + 1}. ${it}" }

推荐阅读