Split a map using Groovy
- by Tihom
I want to split up a map into an array of maps. For example, if there is a map with 25 key/value pairs. I want an array of maps with no more than 10 elements in each map.
How would I do this in groovy?
I have a solution which I am not excited about, is there better groovy version:
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 is the map. Count is the max number of elements within the map.