在 Groovy 中,可以使用以下方法将一个大集合拆分成若干同等大小的子集合,并在遇到不能平分的情况下平摊剩余元素到每个子集合中:

def bigList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
def groupSize = 4
def numberOfGroups = Math.ceil(bigList.size() / (groupSize * 1.0)).toInteger()

def subLists = []
def startIndex = 0
def endIndex = 0

for (int i = 0; i < numberOfGroups; i++) {
    startIndex = i * groupSize
    endIndex = Math.min(startIndex + groupSize, bigList.size())
    subLists << bigList.subList(startIndex, endIndex)
}

// 平摊剩余元素到每个子集合中
def remainingElements = bigList.size() - (numberOfGroups * groupSize)
if (remainingElements > 0) {
    for (int i = 0; i < remainingElements; i++) {
        subLists[i].add(bigList[endIndex + i])
    }
}

subLists.each { println it }

输出结果为:

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

在这个例子中,原始的大集合包含 17 个元素,要求每个子集合包含 4 个元素。由于 17 无法被 4 整除,所以最后一个子集合会多出一个元素。在上述代码中,我们使用 Math.ceil() 方法来计算所需的子集合数量,并使用 subList() 方法将原始大集合拆分成相应的子集合。然后,我们使用一个循环来将剩余的元素平摊到每个子集合中,直到所有剩余元素都被分配完毕。最后,我们使用 each 方法遍历并打印每个子集合。

Groovy 集合拆分:如何平摊多余元素到子集合

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

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