newbie
newbie

Reputation: 119

Groovy - group and sort list

My orginal list is:

[[string: firstString, id: 2], 
[string: secondString, id: 1], 
[string: secondString, id: 3], 
[string: firstString, id: 1], 
[string: firstString, id: 3], 
[string: secondString, id: 2]]

I want to group it by string and sort it by id just like this:

[[string: firstString, id: 1], 
[string: firstString, id: 2], 
[string: firstString, id: 3], 
[string: secondString, id: 1], 
[string: secondString, id: 2], 
[string: secondString, id: 3]]

Upvotes: 1

Views: 1661

Answers (1)

Vampire
Vampire

Reputation: 38649

def firstString = 'first'

def secondString = 'second'

def source =
[[string: firstString, id: 2], 
[string: secondString, id: 1], 
[string: secondString, id: 3], 
[string: firstString, id: 1], 
[string: firstString, id: 3], 
[string: secondString, id: 2]]

Your stated expected result:

def expected =
[[string: firstString, id: 1], 
[string: firstString, id: 2], 
[string: firstString, id: 3], 
[string: secondString, id: 1], 
[string: secondString, id: 2], 
[string: secondString, id: 3]]

def result = source.sort { [it.string, it.id] }
assert result == expected

IDs reversly ordered:

def expected =
[[string: firstString, id: 3], 
[string: firstString, id: 2], 
[string: firstString, id: 1], 
[string: secondString, id: 3], 
[string: secondString, id: 2], 
[string: secondString, id: 1]]

def result = source.sort { [it.string, -it.id] }
assert result == expected

Really grouped, not only sorted by string:

def expected =
[(firstString):
  [[string: firstString, id: 1], 
  [string: firstString, id: 2], 
  [string: firstString, id: 3]], 
(secondString):
  [[string: secondString, id: 1], 
  [string: secondString, id: 2], 
  [string: secondString, id: 3]]]

def result = source.groupBy { it.string }
result.each { it.value.sort { it.id } }
assert result == expected

Really grouped, not only sorted by string, IDs reversely ordered:

def expected =
[(firstString):
  [[string: firstString, id: 3], 
  [string: firstString, id: 2], 
  [string: firstString, id: 1]], 
(secondString):
  [[string: secondString, id: 3], 
  [string: secondString, id: 2], 
  [string: secondString, id: 1]]]

def result = source.groupBy { it.string }
result.each { it.value = it.value.sort { it.id }.reverse() }
assert result == expected

Really grouped and IDs flattened out:

def expected = 
[(firstString): [1, 2, 3], 
(secondString): [1, 2, 3]]

def result = source.groupBy { it.string }
result.each { it.value = it.value.collect { it.id }.sort() }
assert result == expected

Really grouped and IDs flattened out, IDs reversely ordered:

def expected = 
[(firstString): [3, 2, 1], 
(secondString): [3, 2, 1]]

def result = source.groupBy { it.string }
result.each { it.value = it.value.collect { it.id }.sort().reverse() }
assert result == expected

Upvotes: 3

Related Questions