Vano
Vano

Reputation: 1538

groovy map populate with default element

Is there more Groovish way of adding an element to map of lists and initialize default list if not exists?

Or in other words what would be a Groovish way to code the below:

def mylist = [1,2,3,4]
def mymap = [:]

for (num in mylist){
  if (num % 2 == 0){
    pairity = "even"
  } else {
    pairity = "odd"
  }


  if (mymap.containsKey(pairity)){
                println("Adding to Even")
                mymap[pairity].add(num)
  } 
  else {
                println("adding to Odd")
                mymap[pairity] = [num]
  }
}
print(mymap.toString())

// adding to Odd
// adding to Odd
// Adding to Even
// Adding to Even
// [odd:[1, 3], even:[2, 4]]

Upvotes: 1

Views: 790

Answers (2)

cfrick
cfrick

Reputation: 37008

You can use withDefault on a map to have automatically generate a value for a missing key on access.

[1,2,3,4].inject([:].withDefault{[]}){ m, i -> m[ i%2==0 ? 'odd' : 'even' ] << i; m }
// => [even:[1, 3], odd:[2, 4]]

Upvotes: 3

ernest_k
ernest_k

Reputation: 45309

You can simply groupby:

def mymap = mylist.groupBy { it % 2 == 0 ? 'even' : 'odd' }

That is effectively using the closure to partition the list on the condition.

Upvotes: 3

Related Questions