Split a map using Groovy
Posted
by
Tihom
on Stack Overflow
See other posts from Stack Overflow
or by Tihom
Published on 2011-01-06T20:59:12Z
Indexed on
2011/01/06
23:53 UTC
Read the original article
Hit count: 253
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.
© Stack Overflow or respective owner