开发者

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)
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜