Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a map in groovy having two collections - with keys and values

I have two lists:

def ids = [1L, 2L, 3L]
def values = [11, 12, 13]

I would like to create a HashMap with ids as keys and values as values.

I've tried to use transpose but stucked with GroovyCastException

like image 867
pixel Avatar asked Mar 06 '23 18:03

pixel


1 Answers

GroovyCollections.transpose(lists) "zips" elements from two lists, e.g.

[[1,2], [3,4]].transpose() == [[1,3], [2,4]]

You can use it in combination with .collectEntries() to create a map from such output:

Map map = [ids, values].transpose().collectEntries()
assert map == [1: 11, 2: 12, 3: 13]

It will create a map like:

[1:11, 2:12, 3:13]

using your input data.

like image 96
Szymon Stepniak Avatar answered Apr 06 '23 05:04

Szymon Stepniak