Ashish Joseph
Ashish Joseph

Reputation: 1153

Groovy : Getting subLists from a List, based on a field value

How should I group a list of user objects, based on their type. For example, i have a list as below.

List userList = [userA, userB, userC, userD, userE, userF, userH]

And i would like to convert this list into a list.

List userList = [ [userA, userB], [userC, userD, userE, userF], [userH] ] 

Grouped based on the type field of user.

Upvotes: 1

Views: 721

Answers (2)

Sap
Sap

Reputation: 5301

The groovy goodness and only one line of code:-)

def usersByType = users.groupBy({ it.type }).values().toList()

Upvotes: 2

micha
micha

Reputation: 49582

You can use the groupyBy() method:

Map map = users.groupBy { it.type }

This returns a map of user objects grouped by type. The map content looks like this:

[
  typeA : [list of users of typeA], 
  typeB : [list of users of typeB], 
  ..
]

This map can be easily transformed to a list like you need using the collect method:

List l = m.collect { key, value -> value }

Now l is a list that looks like this:

[ [list of users of typeA], [list of users of typeB], .. ]

All in one line:

def list = users.groupBy { it.type } .collect { k, v -> v }

Upvotes: 4

Related Questions