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.
精彩评论