taiyebur - 11 months ago 72

Groovy Question

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;

}

`combineList([1,2,3,4,5,6,7,8,9,0], ['a','b','c','d','e','f'])`

`combineList([1,2,3,4], ['a','b','c','d','e','f'])`

`[1, a, 2, b, 3, c, 4, d, 5, e, 6, f, 7, 8, 9, 0]`

`[1, a, 2, b, 3, c, 4, d, e, f]`

Answer Source

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