Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert associative arrays to map in Groovy

Tags:

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?

like image 307
smeeb Avatar asked Mar 12 '23 01:03

smeeb


1 Answers

You can do it like this:

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

Result:

[fizz:true, buzz:false, bupo:yes]
like image 174
Uros K Avatar answered Apr 07 '23 07:04

Uros K