MarkyMark
MarkyMark

Reputation: 219

Groovy group by more criteria

I have a list of hashmaps

list=[{account:"12345"},{account:null},{account:"12345"},account:null}]

I am grouping them regarding those values account to separate lists

list.groupBy({obj -> obj.account}).values().toList();

The result is those two lists:

[{account:"12345"},{account:"12345"}],[{account:null},{account:null}]

This is correct, but my question is, wheter I can leave the first list as it is and everytime when there is a null value I will get separate list e.g

[{account:"12345"},{account:"12345"}],[{account:null}],[{account:null}]

Or in other words to get 3 lists of maps intead of 2

Upvotes: 1

Views: 389

Answers (1)

daggett
daggett

Reputation: 28564

use UUID instead of null values

(groovy)

def list = [[account:"12345"],[account:null],[account:"12345"],[account:null]]
list.groupBy{obj -> obj.account ?: UUID.randomUUID()}.values().each{println it}

or just new Object

def list=[[account:"12345"],[account:null],[account:"12345"],[account:null]]
list.groupBy{obj -> obj.account ?: new Object()}.values().each{println it}

note that obj.account ?: new Object() will return new Object() for null and empty values of obj.account.

if you need to limit expression only for null values then use obj.account==null ? new Object() : obj.account

Upvotes: 2

Related Questions