grails - 使用 Groovy 分割 map

标签 grails groovy

我想将 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(以避免必须向 MapmetaClass 添加任何内容:

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/

相关文章:

grails - Groovy 类型转换现奇怪

grails - 使用 GPath 深入遍历字符串中带点的 Groovy 对象的方法

java - Jar 找不到主类

Grails 如何从域类的静态方法调用服务?

grails - 基于 IP 地址分配 A/B 测试变体的最佳实践

grails - 如何在 Grails 中外部化自定义约束?

hibernate - 如何在 grails 中有条件的 2 个表左连接

grails - 字段属性如何影响Grails中的域建模?

java - 使用 Java 8 Optional 实现安全的 Map 遍历

grails - 错误 连接被拒绝 : Grails email verification using mail plugin