我想将两个列表的内容交替合并到一个新列表中。列表的长度未定义。我使用以下代码来实现此目的。我想知道,如果有任何groovy方法来实现这一点,而不使用所有的条件和循环。目标是使用常规功能尽可能缩短代码。
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;
}
输入:
案例1:
combineList([1,2,3,4,5,6,7,8,9,0], ['a','b','c','d','e','f'])
案例2:
combineList([1,2,3,4], ['a','b','c','d','e','f'])
输出:
案例1:
[1, a, 2, b, 3, c, 4, d, 5, e, 6, f, 7, 8, 9, 0]
案例2:
[1, a, 2, b, 3, c, 4, d, e, f]
答案 0 :(得分:1)
许多方法之一:
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']
说明:
[[1, a], [2, b], [3, c]]
的列表。 答案 1 :(得分:0)
它也更简单,性能更高:
def combineList( List o, List t ){
def res = [ o, t ].transpose().flatten()
int resSize = res.size() >> 1
if( o.size() > resSize ) res += o[ resSize..-1 ]
else if( t.size() > resSize ) res += t[ resSize..-1 ]
res
}