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)
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With