java - 在 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']
解决方案
你可以这样做:
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}" }
推荐阅读
- android - 超级账本客户端
- kubernetes - 如何使用 python API 以编程方式从 GCP 服务帐户生成 kubernetes 配置
- java - JavaFX11 的 javafx.stage.Stage 版本无效
- django - 如何更新字段实例的选择选项,而不是整个字段?
- arrays - 如何从数组中填充选择器反应本机
- ios - 将 iOS 应用程序连接到蓝牙设备而不是 BLE
- vue.js - 在 VueJS 中是否可以给组件 prop 提供一种以上的类型和多个默认值?
- composer-php - 需要通过作曲家进行本地打包时出错
- excel - 为独立于整列和第一行的行名列表制作公式
- sql - postgresql - 两个大表之间的连接需要很长时间