Sasha Shpota
Sasha Shpota

Reputation: 10300

Transform values of a Map in 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.

Upvotes: 6

Views: 14645

Answers (2)

tim_yates
tim_yates

Reputation: 171084

Not at a computer, but try

map.collectEntries { key, list ->
    [key, list.collectEntries { element ->
        [element, convert(key, element)]
    }]
}

Upvotes: 12

rockympls
rockympls

Reputation: 321

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) }] }

Upvotes: 2

Related Questions