Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Method to combine list of lists

Tags:

list

groovy

Input >> list = [[1,2,3], [6], [3,4,5,6]]  Output >> [1,2,3,3,4,5,6,6]  

I want to know if there is something more straightforward than this

l = [] list.each{ l = l + it } println l 

like a default groovy closure or method?

like image 508
Vamsi Emani Avatar asked Jul 19 '12 10:07

Vamsi Emani


People also ask

How to Combine two lists in Groovy?

Combine lists using the plus operator The plus operator will return a new list containing all the elements of the two lists while and the addAll method appends the elements of the second list to the end of the first one. Obviously, the output is the same as the one using addAll method.

How to add list in Groovy?

Groovy - add() Append the new value to the end of this List. This method has 2 different variants. boolean add(Object value) − Append the new value to the end of this List.


1 Answers

Try flatten, ie:

list.flatten() 

Or, to get the output you want:

list = [[1,2,3], [6], [3,4,5,6]]  assert list.flatten().sort() == [1,2,3,3,4,5,6,6]  
like image 162
tim_yates Avatar answered Sep 30 '22 00:09

tim_yates