我想将两个列表的内容交替合并到一个新列表中。列表的长度是不确定的。我正在使用下面的代码来实现这一目标。我想知道,是否有任何不使用所有条件和循环的方法来实现这一目标。目的是使用常规功能尽可能缩短代码。
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]
多种方式之一:
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]]
。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句