简体   繁体   中英

Groovy groupby or map for a sql

I have written the following query

def result=GuruActivity.executeQuery("select P.id, P.postBy, P.totalUp from GuruActivity as P where P.totalUp>5")
println result
render "done"

I am getting result like

[1, AAA, 7], [2, AAA, 10], [3, AAA, 7], [7, BBB, 7], [9, CCC, 7]

Now how do get the P.ID in the following format (in a map) here i am getting the id that are over 5 totalUp

AAA : [1,2,3]
BBB : [7]
CCC : [9]

How do i do this?

One way is to use collection's groupBy .

def list = [[1, 'AAA', 7], [2, 'AAA', 10], 
           [3, 'AAA', 7], [7, 'BBB', 7], [9, 'CCC', 7]]

assert list.groupBy{it[1]}
           .collectEntries{k, v-> [k, v.collect{it[0]}]} == 
                          ['AAA':[1, 2, 3], 'BBB':[7], 'CCC':[9]]​​​​​​

Another would be inject

list.inject( [:].withDefault { [] } ) { m, e ->
    m[ e[ 1 ] ] << e[ 0 ]
    m
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM