taiyebur taiyebur - 1 month ago 10
Groovy Question

Merge contents of two lists alternately into one list in groovy

I want to merge the contents of two lists alternately into a new list. The length of the lists are undefined. I am using the below code to achieve this. I want to know, if there is any groovy way to achieve this without using all the conditions and loop. The objective is to shorten the code as much as possible using groovy features.

def combineList(ArrayList list1, ArrayList list2){
def list = [];
int j = k = 0;
def size = (list1.size() + list2.size());
for (int i = 0; i < 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]

Answer

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']