I have the following list: appList = [DevOpsApplication, 01.01.01]
I would like to create a map using collectEntries. I know that it refers to the current element of an iteration (shortcut for { it -> it }). Therefore, I tried to use the index:
def appMap = appList.collectEntries { [(it[0]):it[1]] } However, this gives me:
[D:e, 0:1] But I want [DevOpsApplication: 01.01.01]. Is there a way to do this?
Additionally, In future I would like this to expand to more than 2 elements (e.g. [DevOpsApplication, 01.01.01, AnotherDevOpsApplication, 02.02.02]) with the desired output of [DevOpsApplication: 01.01.01, AnotherDevOpsApplication: 02.02.02]. How will this be possible?
3 Answers
A very short version to do this would be:
def appList = ["DevOpsApplication", "01.01.01"] def appMap = [appList].collectEntries() // XXX assert appMap == [DevOpsApplication: "01.01.01"] How does it work: the function collectEntries takes, is expected to return a map or a two element list. Your appList is already that. So put that in another list, call collectEntries on it. When no function is given to collectEntries it uses the identity function.
Bonus: what if appList has much more elements? You can use collate to build the tuples.
def appList = ["DevOpsApplication", "01.01.01", "Some", "More"] def appMap = appList.collate(2).collectEntries() // XXX assert appMap == [DevOpsApplication: "01.01.01", Some: "More"] 0I also found another method. Groovy can convert the values of an Object array and convert them into a map with the toSpreadMap(). However, the array must have an even number of elements.
def appList = ['DevOpsApplication', '01.01.01'] def appMap = appList.toSpreadMap() 1You're iterating element-by-element and (because your elements are String-typed) mapping 0 substrings to 1 substrings.
You can use this to skip one element in each iteration and map each element at even indices to the one after it:
def appList = ['DevOpsApplication', '01.01.01'] def appMap = (0..(appList.size()-1)).findAll{0 == it%2} .collectEntries{[(appList[it]): appList[it+1]]} That returns [DevOpsApplication:01.01.01] as expected.