Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform values of a Map in groovy

Tags:

groovy

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.

like image 202
Sasha Shpota Avatar asked Jul 18 '17 15:07

Sasha Shpota


People also ask

How do I convert a list to map in Groovy?

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.

How do I create a map object in Groovy?

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.

What is Groovy hash map?

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.

How do I merge two maps in Groovy?

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.


2 Answers

Not at a computer, but try

map.collectEntries { key, list ->
    [key, list.collectEntries { element ->
        [element, convert(key, element)]
    }]
}
like image 187
tim_yates Avatar answered Sep 28 '22 16:09

tim_yates


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) }] }
like image 45
rockympls Avatar answered Sep 28 '22 15:09

rockympls