0

I'm using collectEntries to build a map from a different map. However when I try to get the values based on the keys. It returns null, even though when I print the entire map the key is there.

static void main(String[] args) {
    Map<String, List<String>> multiMap = ['apple': ['granny', 'delicious']]
    Map m = multiMap.collectEntries { String k, List<String> v ->
        v.collectEntries { String subkey -> ["${k}-${subkey}": subkey] }
    }

    println m
    println m.keySet()
    println m['apple-granny']
    println m[m.keySet()[0]]
}

The output is:

[apple-granny:granny, apple-delicious:delicious]
[apple-granny, apple-delicious]
null
null

Why can't I retrieve the value from the map? How should I be doing it?

Dan N
  • 167
  • 1
  • 7

1 Answers1

2

Because your key is a GString instance, not a String.. (See, many, questions, on, here, about this issue)

Change your collectEntries line to:

    v.collectEntries { String subkey -> [("${k}-${subkey}".toString()): subkey] }

To force the key as a String and it will work fine

Community
  • 1
  • 1
tim_yates
  • 167,322
  • 27
  • 342
  • 338