我想将 map 拆分为 map 数组。例如,如果有一个包含 25 个键/值对的映射。我想要一个 map 数组,每个 map 中的元素不超过 10 个。
我该如何在 groovy 中做到这一点?
我有一个我不感兴趣的解决方案,是否有更好的常规版本:
static def splitMap(m, count){
if (!m) return
def keys = m.keySet().toList()
def result = []
def num = Math.ceil(m?.size() / count)
(1..num).each {
def min = (it - 1) * count
def max = it * count > keys.size() ? keys.size() - 1 : it * count - 1
result[it - 1] = [:]
keys[min..max].each {k ->
result[it - 1][k] = m[k]
}
}
result
}
m是 map 。计数是 map 内元素的最大数量。
最佳答案
Adapting my answer to this question on partitioning a List ,我想出了这个方法:
Map.metaClass.partition = { size ->
def rslt = delegate.inject( [ [:] ] ) { ret, elem ->
( ret.last() << elem ).size() >= size ? ret << [:] : ret
}
rslt.last() ? rslt : rslt[ 0..-2 ]
}
所以如果你拿这张 map :
def origMap = [1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f']
以下所有断言均通过:-)
assert [ [1:'a'], [2:'b'], [3:'c'], [4:'d'], [5:'e'], [6:'f'] ] == origMap.partition( 1 )
assert [ [1:'a', 2:'b'], [3:'c', 4:'d'], [5:'e', 6:'f'] ] == origMap.partition( 2 )
assert [ [1:'a', 2:'b', 3:'c'], [4:'d', 5:'e', 6:'f'] ] == origMap.partition( 3 )
assert [ [1:'a', 2:'b', 3:'c', 4:'d'], [5:'e', 6:'f'] ] == origMap.partition( 4 )
assert [ [1:'a', 2:'b', 3:'c', 4:'d', 5:'e'], [6:'f'] ] == origMap.partition( 5 )
assert [ [1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f'] ] == origMap.partition( 6 )
<小时/>
或者,作为 Category
(以避免必须向 Map
的 metaClass
添加任何内容:
class MapPartition {
static List partition( Map delegate, int size ) {
def rslt = delegate.inject( [ [:] ] ) { ret, elem ->
( ret.last() << elem ).size() >= size ? ret << [:] : ret
}
rslt.last() ? rslt : rslt[ 0..-2 ]
}
}
然后,当您需要此功能时,您可以简单地使用
类别,如下所示:
use( MapPartition ) {
assert [ [1:'a'], [2:'b'], [3:'c'], [4:'d'], [5:'e'], [6:'f'] ] == origMap.partition( 1 )
assert [ [1:'a', 2:'b'], [3:'c', 4:'d'], [5:'e', 6:'f'] ] == origMap.partition( 2 )
assert [ [1:'a', 2:'b', 3:'c'], [4:'d', 5:'e', 6:'f'] ] == origMap.partition( 3 )
assert [ [1:'a', 2:'b', 3:'c', 4:'d'], [5:'e', 6:'f'] ] == origMap.partition( 4 )
assert [ [1:'a', 2:'b', 3:'c', 4:'d', 5:'e'], [6:'f'] ] == origMap.partition( 5 )
assert [ [1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f'] ] == origMap.partition( 6 )
}
关于grails - 使用 Groovy 分割 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4619794/