在Groovy中,我们可以使用多个groupBy和max函数来实现对数据集进行多重分组和获取最大值的操作。
首先,groupBy函数可以用于对数据集按照指定的属性进行分组。我们可以使用collect方法结合groupBy函数来实现多个groupBy的效果。下面是一个示例代码:
def data = [
[name: "Alice", age: 25, city: "Beijing"],
[name: "Bob", age: 30, city: "Shanghai"],
[name: "Alice", age: 35, city: "Beijing"],
[name: "Bob", age: 40, city: "Shanghai"],
[name: "Alice", age: 45, city: "Beijing"]
]
def result = data.groupBy { it.name }.collectEntries { k, v ->
[k, v.groupBy { it.city }]
}
println result
上述代码将根据姓名和城市对数据进行分组,并输出结果:
[
Alice: [
Beijing: [
[name: Alice, age: 25, city: Beijing],
[name: Alice, age: 35, city: Beijing],
[name: Alice, age: 45, city: Beijing]
]
],
Bob: [
Shanghai: [
[name: Bob, age: 30, city: Shanghai],
[name: Bob, age: 40, city: Shanghai]
]
]
]
接下来,我们可以使用max函数来获取每个分组中的最大值。再次利用collect方法,可以实现对多个分组的最大值获取。以下是示例代码:
def data = [
[name: "Alice", age: 25, city: "Beijing"],
[name: "Bob", age: 30, city: "Shanghai"],
[name: "Alice", age: 35, city: "Beijing"],
[name: "Bob", age: 40, city: "Shanghai"],
[name: "Alice", age: 45, city: "Beijing"]
]
def result = data.groupBy { it.name }.collectEntries { k, v ->
[k, v.groupBy { it.city }.collectEntries { k2, v2 ->
[k2, v2.max { it.age }]
}]
}
println result
上述代码将获取每个姓名分组中每个城市分组的年龄最大值,并输出结果:
[
Alice: [
Beijing: [name: Alice, age: 45, city: Beijing]
],
Bob: [
Shanghai: [name: Bob, age: 40, city: Shanghai]
]
]
通过以上示例代码,我们可以在Groovy中使用多个groupBy和max函数实现多重分组和获取最大值的操作。在实际应用中,可以根据具体需求进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云