Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting values from nested lists in groovy

I have a 3 level nested list in groovy like this

rList = [[[12, name1],[22,name2],[49,name3]],[[33, name5],[22,name6],[21, name7]]]

how can I iterate it to get the name values from the 1st sublist so I want like rsublist = [name1, name2, name3]

Thanks in advance.

like image 830
pri_dev Avatar asked Jun 10 '12 03:06

pri_dev


1 Answers

rList = [[[12, 'name1'], [22, 'name2'], [49, 'name3']], [[33, 'name5'], [22, 'name6'], [21, 'name7']]]
names = rList[0]*.getAt(1)
assert names == ['name1', 'name2', 'name3']

First, rList[0] gives you the first sub-list, which is [[12, name1], [22, name2], [49, name3]]. Then, the spread operator, *., is used to apply the same method, getAt(1), to every element of that list, which will return a list with every second element of the sub-lists, which are the values you were looking for :)

You can also use rList[0].collect { it[1] } which is equivalent and might be more familiar if you are not used to the spread operator.

like image 108
epidemian Avatar answered Oct 09 '22 14:10

epidemian