Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of Maps into Single Map In Groovy

I have a list of map like below:

List mapOne = [[hi:1], [hello:2],[xyx:4]]

This map should be converted to one single map like below

Map resultMap=[hi:1, hello:2,xyx:4]

Do we have any built in functions in Groovy?

like image 414
Raju Avatar asked Jun 30 '17 11:06

Raju


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 Hashmap?

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. Morten.


2 Answers

Just do:

Map resultMap = mapOne.collectEntries()
like image 160
tim_yates Avatar answered Sep 18 '22 10:09

tim_yates


Another option is sum:

groovy:000> [[hi:1], [hello:2], [xyx:4]].sum()
===> [hi:1, hello:2, xyx:4]
like image 29
cfrick Avatar answered Sep 20 '22 10:09

cfrick