Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

groovy

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)
}
like image 235
Yossale Avatar asked Aug 08 '11 07:08

Yossale


People also ask

How do you add a map to Groovy?

You can achieve that with simply using java. create a map say x and put type and value in that map and add this in a list say userKnown and then create a map and add this userKnown in userKnownVariable. That's it.

How do I iterate a map in Groovy?

If you wanted to do it that way, iterate over map. keySet() and the rest will work as you expected. It should work if you use s. key & s.

Are Groovy maps ordered?

Maps don't have an order for the elements, but we may want to sort the entries in the map. Since Groovy 1.7. 2 we can use the sort() method which uses the natural ordering of the keys to sort the entries. Or we can pass a Comparator to the sort() method to define our own sorting algorithm for the keys.


1 Answers

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.

like image 86
Tomasz Nurkiewicz Avatar answered Sep 20 '22 04:09

Tomasz Nurkiewicz