在 Groovy 中,可以使用集合的collate()方法将一个大集合拆分成若干同等大小的子集合。如果无法平分,则会将剩余的元素平摊到每个子集合中。

以下是一个示例代码:

def largeList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def subsetSize = 4

def subsets = largeList.collate(subsetSize)

subsets.each { subset ->
    println subset
}

输出结果:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15]

在上述示例中,collate()方法将largeList拆分成了4个子集合,每个子集合的大小为4。注意到最后一个子集合只有3个元素,这是因为无法平分,所以剩余的元素会平摊到每个子集合中。

Groovy 集合拆分:如何将大集合分成同等大小的子集合并处理余数

原文地址: http://www.cveoy.top/t/topic/iXcD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录