如何查找grails中每个元素的出现次数?

时间:2016-07-01 12:21:03

标签: grails

我想计算所有数字及其出现次数 比如1 = 4,2 = 3等

def list=[1,1,1,2,1,2,3,2,3,4,9,4,6,3,6]

2 个答案:

答案 0 :(得分:3)

assert list.countBy { it } == [1:4, 2:3, 3:3, 4:2, 9:1, 6:2]

答案 1 :(得分:-1)

def list=[1,1,1,2,2,2,3,3,1,6,4,6,5,4]
def countMap=[:]
 list.each{
  if(countMap[it]){
   countMap[it]=countMap[it]+1
  }else{
   countMap[it]=1
  }
}