从几个列表中,我需要创建一个结果列表,其中所有其他值的值使用循环算法选择数据。
list1 = val1_1,val1_2 ..
list2 = val2_1,val2_2 ..
list3 = val3_1,val3_2 ..
//rr choosing
result = val1_1,val2_1,val3_1,val1_2,val2_2,val3_2,val1_3...
答案 0 :(得分:2)
您可以使用从各个列表中派生的v4.0.30319
Queue
。从队列中获取下一个迭代器,从迭代器中获取下一个元素,如果它不为空,则将其添加回队列。
Iterators
答案 1 :(得分:2)
如果您想创建一个一维列表,其中填充来自锯齿状二维列表列中的数据,您可以使用两个嵌套的 for 循环:首先按列,然后按行。如果您事先不知道最大行的长度,即列数,您可以迭代,直到列仍然存在于至少一行中。
// input data
List<List<String>> lists = Arrays.asList(
Arrays.asList("a1", "b1", "c1"),
Arrays.asList("a2", "b2"),
Arrays.asList("a3", "b3", "c3", "d3"));
// result list
List<String> listRobin = new ArrayList<>();
// iteration over the columns of a 2d list until
// the columns are still present at least in one row
for (int col = 0; ; col++) {
// whether the columns are still present
boolean max = true;
// iteration over the rows, i.e. lists
for (List<String> list : lists) {
// if column is present
if (col < list.size()) {
// take value from this column
listRobin.add(list.get(col));
// columns are still present
max = false;
}
}
// if there are no more columns
if (max) break;
}
// output
System.out.println(listRobin);
// [a1, a2, a3, b1, b2, b3, c1, c3, d3]
另见:
• Join lists in java in round robin fashion
• How do you rotate a 2D array 90 degrees without using a storage array?
答案 2 :(得分:1)
列表长度相同
public static void main(String[] args) {
String[][] values = new String[][] {
{ "1_1", "1_2", "1_3" },
{ "2_1", "2_2", "2_3" },
{ "3_1", "3_2", "3_3" }
};
for (int count = 0; count < values.length * values[0].length; count++) {
System.out.println(values[count % values.length][count / values[0].length]);
}
}
表达式:
count % values.length
在所有行之间旋转,而表达式为:
count / values[0].length
逐行增加一次迭代次数。
列表有不同的长度
public static void main(String[] args) {
String[][] values = new String[][] {
{ "1_1", "1_2", "1_3" },
{ "2_1", "2_2" },
{ "3_1", "3_2", "3_3", "3_4" }
};
for (int count = 0, maxLen = 0;; count++) {
int row = count % values.length;
int col = count / values[0].length;
maxLen = Math.max(values[row].length, maxLen);
if (values[row].length > col) {
System.out.println(values[row][col]);
} else if (row + 1 == values.length && col >= maxLen) break;
}
}
为具有相同长度的列表提供的解决方案的差异是: