Groovy集合常用简洁语法

发布于:2025-09-01 ⋅ 阅读:(13) ⋅ 点赞:(0)

Groovy 集合(Collections)提供了大量简洁且强大的语法,以下是对常用操作的详细说明,涵盖 List、Map、Set 等集合类型:


一、集合创建

1. 列表(List)
def list1 = [1, 2, 3]                    // 可变列表
def list2 = [1, 2, 3] as ArrayList       // 显式指定类型
def emptyList = []                       // 空列表
def rangeList = (1..5)                   // 范围生成列表 [1,2,3,4,5]
2. 映射(Map)
def map = [a: 1, b: 2]                   // 创建Map(键默认视为字符串,无需引号)
def explicitMap = ['a': 1, 'b': 2]       // 显式字符串键
def emptyMap = [:]                       // 空Map
3. 集合(Set)
def set = [1, 2, 3] as Set              // 去重集合
def emptySet = [] as Set

二、常用操作

1. 遍历元素
list.each { println it }                 // 遍历每个元素
list.eachWithIndex { item, index ->      // 带索引遍历
    println "$index: $item"
}
2. 元素查找
def found = list.find { it > 2 }         // 找第一个匹配的元素
def allMatches = list.findAll { it % 2 == 0 }  // 找所有偶数
def anyMatch = list.any { it > 5 }       // 是否存在满足条件的元素
def everyMatch = list.every { it < 10 }  // 是否所有元素都满足条件
3. 集合转换
def squared = list.collect { it * it }    // 转换为新列表 [1,4,9]
def flattened = nestedList.flatten()      // 扁平化嵌套列表
def combined = list1 + list2              // 合并列表
def subtracted = list1 - list2            // 移除交集
4. 排序与去重
def sorted = list.sort()                  // 自然排序
def customSorted = list.sort { a, b -> b <=> a }  // 自定义排序(降序)
def unique = list.unique()                // 去重(原地修改)
def distinct = list.toUnique()            // 返回去重后的新集合
5. 分组与分类
def grouped = list.groupBy { it % 2 }     // 按奇偶分组:{0=[2,4], 1=[1,3]}
def partitioned = list.split { it > 2 }   // 分割为两个列表:[[1,2], [3,4,5]]

三、Map 专用操作

1. 遍历 Map
map.each { key, value -> println "$key: $value" }
map.each { entry -> println entry.key }
2. 键/值操作
def keys = map.keySet()                   // 所有键
def values = map.values()                 // 所有值
map.put('c', 3)                           // 添加元素
map.remove('a')                           // 移除键 'a'
3. 默认值处理
def value = map.getOrDefault('d', 0)      // 若键不存在返回默认值
def value2 = map.d                        // 类似属性访问(键不存在返回 null)

四、集合注入(Inject/Reduce)

def sum = list.inject(0) { acc, val -> acc + val }  // 求和(类似 reduce)
def product = list.inject(1) { acc, val -> acc * val }

五、惰性求值(Lazy Evaluation)

def lazySquared = list.lazyCollect { it * it }  // 惰性转换(Groovy 3.0+)
def filtered = list.findResults { it > 2 ? it * 2 : null }  // 过滤并转换(忽略 null)

六、其他实用操作

1. 随机元素
def randomItem = list.shuffled().first()  // 随机打乱并取第一个
2. 最小/最大值
def min = list.min()
def max = list.max()
def maxByLength = list.max { it.length() }  // 按条件找最大
3. 交集与并集
def intersection = list1.intersect(list2)  // 交集
def union = list1 + list2                 // 并集(需手动去重)

七、注意事项

  1. 默认类型:Groovy 集合默认是可变(mutable)的,如需不可变集合,使用:

    def immutableList = [1, 2, 3].asImmutable()

  2. 安全访问:使用 ?. 避免空指针:

    def size = list?.size()  // 若 list 为 null 返回 null

  3. 性能考虑:大数据集时优先使用 find 而非 findAll,避免不必要的遍历。


示例汇总

// 创建并处理列表
def numbers = [1, 2, 3, 4, 5]
def evenSquares = numbers.findAll { it % 2 == 0 }
                         .collect { it * it }
                         .join(', ')  // 输出 "4, 16"

// 分组处理字符串列表
def words = ['apple', 'banana', 'cherry']
def byLength = words.groupBy { it.length() }  // {5=['apple'], 6=['banana', 'cherry']}

Groovy 的集合语法极大简化了数据处理代码,结合闭包特性,可高效实现复杂操作。


网站公告

今日签到

点亮在社区的每一天
去签到