Merge contents of two lists alternately into one list in groovy -
i want merge contents of 2 lists alternately new list. length of lists undefined. using below code achieve this. want know, if there groovy way achieve without using conditions , loop. objective shorten code as possible using groovy features.
def combinelist(arraylist list1, arraylist list2){ def list = []; int j = k = 0; def size = (list1.size() + list2.size()); (int = 0; < size; i++) { if(j < list1.size()) list.add(list1.get(j++)); if(k < list2.size()) list.add(list2.get(k++)); } println list; }
input:
case 1:
combinelist([1,2,3,4,5,6,7,8,9,0], ['a','b','c','d','e','f'])
case 2:
combinelist([1,2,3,4], ['a','b','c','d','e','f'])
output:
case 1:
[1, a, 2, b, 3, c, 4, d, 5, e, 6, f, 7, 8, 9, 0]
case 2:
[1, a, 2, b, 3, c, 4, d, e, f]
one of many ways:
list combinelist(list one, list two) { def result = [one, two].transpose() ( result += (one - result*.get(0)) ?: (two - result*.get(1)) ).flatten() } assert combinelist([1,2,3,4], ['a','b','c','d','e','f']) == [1, 'a', 2, 'b', 3, 'c', 4, 'd', 'e', 'f'] assert combinelist([1,2,3,4,5,6,7,8,9,0], ['a','b','c','d','e','f']) == [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e', 6, 'f', 7, 8, 9, 0] assert combinelist([1,2,3,4], ['a','b','c','d']) == [1, 'a', 2, 'b', 3, 'c', 4, 'd']
explanation:
- transposing lists results list
[[1, a], [2, b], [3, c]]
. - next check if there residual elements left in either of list.
- this done checking if minus operation results elements. take first elements result list check against first list parameter, take second elements of result list check against second list passed parameter method.
- if present, add them result
- finally, flatten result
Comments
Post a Comment