Divide the map using Groovy

I want to split a map into an array of maps. For example, if there is a card with 25 key / value pairs. I want an array of no more than 10 elements to be displayed on each map.

How would this be done in groovy?

I have a solution that doesn't bother me if there is a 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 mapping. Count - the maximum number of elements on the map.

+3
source share
1 answer

Adapting my answer to this question when splitting the list , I came up with this method:

Map.metaClass.partition = { size ->
  def rslt = delegate.inject( [ [:] ] ) { ret, elem ->
    ( ret.last() << elem ).size() >= size ? ret << [:] : ret
  }
  rslt.last() ? rslt : rslt[ 0..-2 ]
}

So if you take this card:

def origMap = [1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f']

All of the following statements pass :-)

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 )

Or, like a Category(so as not to add anything to metaClassin Map:

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 ]
  }
}

Then, where you need this functionality, you can simply useCategory, for example:

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 )
}
+6
source

Source: https://habr.com/ru/post/1783940/


All Articles