Lets say I have a map Map<String, List<Integer>>
.
I want to transform this map into Map<String, Map<Integer, Object>>
by applying convert()
method for each pair of key and element of nested list.
Object convert(String key, Integer value)
How can I achieve that?
I tried something like this:
map.collect { key, list ->
key: list.collectEntries {
[(element): convert(key, element)]
}
}
but I'm getting ClassCastException: ArrayList cannot be cast to Map
.
Using a SpreadMap we will convert a list of strings into a map. A SpreadMap is a helper that turns a list with an even number of elements into a Map. In the snippet below, we create a map keyed by NFL city while the value will be the team name.
2. Creating Groovy Maps. We can use the map literal syntax [k:v] for creating maps. Basically, it allows us to instantiate a map and define entries in one line.
A hashmap maps a key to a value, but you are trying to map a key to two values. To do this, create a hashmap, where the key is your ID and the value is another hashmap, mapping the string "firstname" to "Jack" and the string "lastname" to "Sparrow" and so on for all <person> elements.
Merge maps using + operator The easiest way to merge two maps in Groovy is to use + operator. This method is straightforward - it creates a new map from the left-hand-side and right-hand-side maps.
Not at a computer, but try
map.collectEntries { key, list ->
[key, list.collectEntries { element ->
[element, convert(key, element)]
}]
}
You can simplify it a little:
def convert = { it -> it + 1 };
Map<String, List<Integer>> map = [foo: [1, 2, 3], bar: [4, 5, 6]];
map.collectEntries { k, v -> [(k): v.collect { convert(it) }] }
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