使用Groovy拆分地图

Tih*_*hom 3 grails groovy

我想将地图拆分成一组地图.例如,如果存在具有25个键/值对的映射.我想要一个每个地图中不超过10个元素的地图数组.

我如何在groovy中这样做?

我有一个我不感兴趣的解决方案,有更好的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
  }
Run Code Online (Sandbox Code Playgroud)

m是地图.Count是地图中元素的最大数量.

tim*_*tes 6

在分区列表中调整我对这个问题的答案时,我想出了这个方法:

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

所以如果你拿这张地图:

def origMap = [1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f']
Run Code Online (Sandbox Code Playgroud)

所有以下断言都通过:-)

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 )
Run Code Online (Sandbox Code Playgroud)

或者,作为Category(以避免添加任何东西到metaClassMap:

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 ]
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,在需要此功能的地方,您可以use像这样简单地使用类别:

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 )
}
Run Code Online (Sandbox Code Playgroud)