Groovy iterate over Map

I am having a groovy map which holds this kinda values

Map testMap = [1:[1,1,1],2:[2,2,2]]

Here when I call collect function like this

testMap.collect {it.value}

I getting the output like

[[1, 1, 1], [2, 2, 2]]

But I want the output as [1,1,1,2,2,2]

is their any groovy method to achieve this, without using each method

Upvotes: 2

Views: 2829

Answers (3)

Mark Fisher
Mark Fisher

Reputation: 9886

A couple of the solutions here use the collect family, which is ok if you're doing mutations on the data, but in this case it's just grabbing all the values which would be better served using the spread operator on the values of the map

testMap*.value.flatten()

or with functions on the map

testMap.values().flatten()

Note it's value when spreading over each element of the map, and values() when asking the map directly in one go for the entries values.

Both of these read more as "getting values out of testMap" rather than collect which is usually used for mutations on the map.

It's a matter of style, but if you only use collect when you're going to mutate the data, you'll have more readable code.

Upvotes: 7

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1345

There is even simplier solution

 [1:[1,1,1],2:[2,2,2]].collectMany{it.value}

Upvotes: 7

ABC
ABC

Reputation: 4373

You can use groovy's flatten() method.

testMap.collect {it.value}.flatten()

Upvotes: 7

Related Questions