如何通过以循环方式合并 3 个 ArrayList 来创建新列表? [英] How to create a new List from merging 3 ArrayLists in round robin style?
本文介绍了如何通过以循环方式合并 3 个 ArrayList 来创建新列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 3 个数组.我想合并 3 个数组并创建一个显示所有合并整数的新数组.我希望这个新数组采用循环方式.
I have 3 arrays. I want to merge the 3 arrays and create a new array that shows all the merged integers. I would like this new array to be in round robin style.
示例输入:
array = {arr1 = 1, 2, 3, arr2 = 4, 5, 6, arr3 = 7, 8, 9}
示例输出:
arr4 = 1, 4, 7, 2, 5, 8, 3, 6, 9
我应该使用此功能,但我不明白如何使用 listOfLists
:
I'm supposed to use this function but I don't understand how can I use a listOfLists
:
String roundRobin(List<List<Integer>>listOfLists) {
推荐答案
我认为循环输入和获取元素并将元素添加到数组列表中很容易理解.
I think just loop input and get element and add element to a list of array is easy to understand.
public static List<Integer> roundRobin(List<List<Integer>> listOfLists) {
if (listOfLists == null || listOfLists.isEmpty()) {
return new ArrayList<>();
}
int maxLength = -1;
for (List<Integer> list : listOfLists) {
if (list.size() > maxLength) {
maxLength = list.size();
}
}
List<Integer> result = new ArrayList<>(maxLength * listOfLists.size());
for (int i = 0; i < maxLength; i++) {
for (List<Integer> list : listOfLists) {
if (i < list.size()) {
result.add(list.get(i));
}
}
}
return result;
}
这篇关于如何通过以循环方式合并 3 个 ArrayList 来创建新列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文