smeeb smeeb - 2 months ago 10
Groovy Question

Convert associative arrays to map in Groovy

I have two

String[]
with identical lengths. They are "associative arrays" in the sense that the string values of one are the keys and the string values in the other are the values:

String[] keys = { 'fizz', 'buzz', 'bupo' }
String[] values = { 'true', 'false', 'yes' }


I want to take these two associative arrays and convert them into a
Map<String,String>
with some Groovy magic. So far I have tried the following but it is not working:

Map<String,String> kvPairs = [keys, values]


Any ideas where I'm going awry?

Answer

You can do it like this:

String[] keys = [ "fizz", "buzz", "bupo" ] as String[]
String[] vals = [ "true", "false", "yes" ] as String[]
Map<String, String> kvPairs = [ keys, vals ].transpose()​.collectEntries()​

Result:

[fizz:true, buzz:false, bupo:yes]
Comments