Yossale
Yossale

Reputation: 14361

A Groovy way to add element to a list in a map?

I have a Map of Int->List[Int], and given a value I want to check if it already has an entry. If so, add to the list. Otherwise, create a new list and add to it. Is there a shorter way to do this?

def map = [:]

(1..100).each { i ->
    if (map[i % 10] == null) {
        map[i % 10] = []
    }
    map[i % 10].add(i)
}

Upvotes: 9

Views: 9733

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

Use map with default value:

def map = [:].withDefault {[]}

(1..100).each {map[it % 10].add(it)}

The default value will be created every time you try to access non-existing key.

Upvotes: 23

Related Questions