2

我来自 PHP 世界,我需要做一些记录统计。在 php 中我知道这很简单,但是如何在 Groovy 中执行以下操作

$logs = array( array( 'date' => '5-15', 'name' => 'foo' ...other stuff),
               array( 'date' => '5-15', 'name' => 'bar' ...other stuff),
               array( 'date' => '5-16', 'name' => 'foo' ...other stuff),
               array( 'date' => '5-17', 'name' => 'foo' ...other stuff),
               array( 'date' => '5-17', 'name' => 'foo' ...other stuff),
               array( 'date' => '5-17', 'name' => 'bar' ...other stuff),
               array( 'date' => '5-17', 'name' => 'bar' ...other stuff) );

$counts = array();

foreach($logs as $log) {
   if( isset($counts[ $log['date'] ][ $log['name'] ]) ) {
       $counts[ $log['date'] ][ $log['name'] ] = 1;
   } else {
       $counts[ $log['date'] ][ $log['name'] ]++;
   }
}

这给了我结果

['5-15']['foo'] = 1
['5-15']['bar'] = 1
['5-16']['foo'] = 1
['5-17']['foo'] = 2
['5-17']['bar'] = 2

日志实际上是我从 GORM 查询返回的结果集。

4

2 回答 2

4

您可以使用 Groovy countBy

def map = logs.countBy{[it.date, it.name]}

您最终会得到一张结果图和相应的计数。在你的情况下,它会像

[[5-15, foo]:1, [5-15, bar]:1, [5-16, foo]:1, [5-17, foo]:2, [5-17, bar]:2]

样本

def logs = [
        [ date: '5-15', name: 'foo'],
        [ date: '5-15', name: 'bar'],
        [ date: '5-16', name: 'foo'],
        [ date: '5-17', name: 'foo'],
        [ date: '5-17', name: 'foo'],
        [ date: '5-17', name: 'bar'],
        [ date: '5-17', name: 'bar']]

def map = logs.countBy{[it.date, it.name]}

assert map[['5-15', 'foo']] == 1
assert map[['5-15', 'bar']] == 1
assert map[['5-16', 'foo']] == 1
assert map[['5-17', 'foo']] == 2
assert map[['5-17', 'bar']] == 2

如果您需要从地图中获取each该对。<key,value>你可以非常喜欢:-

map.each{k, v ->
    println "$k has been used $v times"
}

//Prints:
[5-15, foo] has been used 1 times
[5-15, bar] has been used 1 times
[5-16, foo] has been used 1 times
[5-17, foo] has been used 2 times
[5-17, bar] has been used 2 times

在 Groovy 2.1.3 中测试

于 2013-05-31T20:03:37.140 回答
2

这是在计数映射中使用复合键。不过,您可以用其他方式对其进行切片和切丁。

def logs = [
        [ date: '5-15', name: 'foo'],
        [ date: '5-15', name: 'bar'],
        [ date: '5-16', name: 'foo'],
        [ date: '5-17', name: 'foo'],
        [ date: '5-17', name: 'foo'],
        [ date: '5-17', name: 'bar'],
        [ date: '5-17', name: 'bar']]

def counts = [:]         
logs.collectEntries(counts) { 
    def key = [it.date, it.name]
    def count = counts[key] ?: 0
    [key, count + 1]
}


assert counts[['5-15', 'foo']] == 1
assert counts[['5-15', 'bar']] == 1
assert counts[['5-16', 'foo']] == 1
assert counts[['5-17', 'foo']] == 2
assert counts[['5-17', 'bar']] == 2
于 2013-05-31T20:03:20.437 回答