A groovy way to add an item to a list on a map?

I have an Int-> List [Int] map and a value is set that I want to check if it already has an entry. If yes, add to the list. Otherwise, create a new list and add 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) } 
+8
groovy
source share
1 answer

Use a card with a default value:

 def map = [:].withDefault {[]} (1..100).each {map[it % 10].add(it)} 

A default value will be created each time you try to access a key that does not exist.

+21
source share

All Articles