Groovy List: group By number of items and searches for items with the highest frequency

I have a groovy list as below

def certs = ['0xc1','0xc1','0xc1','0xc1','0xc2','0xc2','0xc3','0xc4','0xc4','0xc5','0xc5','0xc5','0xc5']

I try to find the randomness of each element and group by its score. I tried

certs.groupBy { it }.findAll { it.value.size() }

but I get the following output

[0xc1:[0xc1, 0xc1, 0xc1, 0xc1], 0xc2:[0xc2, 0xc2], 0xc3:[0xc3], 0xc4:[0xc4, 0xc4], 0xc5:[0xc5, 0xc5, 0xc5, 0xc5]]

Instead, expect below

[0xc1:4, 0xc2:2, 0xc3:1, 0xc4:2, 0xc5:4]

can someone help me with this? Also, I want to find the maximum of the occurring element in the list in my case 0xc1and0xc5

UPDATE:

def myMap = certs.inject([:]) { m, x -> if (!m[x]) m[x] = 0; m[x] += 1; m }
def maxValue = myMap.values().max{it} 
def myKeys = []
myMap.findAll{ it.value == maxValue }.each{myKeys << it?.key}
println myKeys  // result = [0xc1:4, 0xc5:4]
//println myMap.sort { a, b -> b.value <=> a.value }
+4
source share
2 answers

There are several ways to do this. A good place to learn Groovy collection methods is collection and input.

The collect method generates a new collection for the old one, making a closure that describes how to modify each element of the existing collection to get a new element for the new collection.

inject . , : , , . - ( , ).

, , :

m = certs.inject([:]) { m, x -> if (!m[x]) m[x] = 0; m[x] += 1; m }

certs, ,

[0xc1:4, 0xc2:2, 0xc3:1, 0xc4:2, 0xc5:4]

. , , .

groupBy, , . , collect, , collectEntries, , :

certs.groupBy().collectEntries { [(it.key) : it.value.size()] }

, Groovy 1.8, countBy, , . .

,

maxSize = m.values().max
m.entrySet().findAll { it.value == maxSize }
+5
Map counts = certs.countBy { it }
counts.findAll { it.value == counts.values().max() }

certs.countBy { it }.groupBy { it.value }.max { it.key }.value.keySet()
+10

All Articles