How do you use GroupBy and Sum together in Groovy?

I have a collection as such:

[[patient1,value1], [patient2,value2]] 

For instance.
x = [[1, 20.28], [1, 11.11], [2, 4.60], [2, 3.68]]

I use countBy to get counts per patient:

 def counts = x.countBy{patient, value -> patient} 

I am trying to get amounts per patient with no luck:

 def sums = x.groupBy({patient, value -> patient }).collectEntries{p, v -> p:v.sum()} 

Is there something I am missing?

Note. The overall goal here is to get the patient averages that I use:

 def avgs = sums.collect{patient, value -> (value / counts[patient]) } 

Thanks!

+5
source share
1 answer

In the groupBy method, the closure identifies what you want to group, the list items are obtained using the grouped value:

 x.groupBy { it[0] } // map entries by patient number 

estimated as

 [1:[[1, 20.28], [1, 11.11]], 2:[[2, 4.60], [2, 3.68]]] 

The collectEntries method tells how to make each map element look like, given that each input for collectEntries has a patient number for the key and a list of pairs for this key for the value. So

 x.groupBy {it[0]}.collectEntries {[(it.key): it.value.sum {it[1]}]} 

estimated as

 [1:31.39, 2:8.28] 

On average, there will be one patient

 x.groupBy {it[0]}.collectEntries {[(it.key): it.value.sum {it[1]}/it.value.size()]} 

evaluating the value of [1:15.695, 2:4.14]

The average value of the average values:

 def avgs = [1:15.695, 2:4.14] def averageOfAverages = avgs.entrySet().sum {it.value} / avgs.size() 
+6
source

Source: https://habr.com/ru/post/1238883/


All Articles