在我看来,您正在寻找的是transpose()
适用于列表列表的功能
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
List<String> list3 = new ArrayList<String>();
list1.add("list11");
list1.add("list12");
list1.add("list13");
list2.add("list21");
list2.add("list22");
list3.add("list31");
list3.add("list32");
list3.add("list33");
list3.add("list34");
List<List<String>> container = new ArrayList<List<String>>();
container.add(list1);
container.add(list2);
container.add(list3);
printList(container);
List<List<String>> transposed = transpose(container);
printList(transposed);
}
private static void printList(List<List<String>> transposed) {
for (List<String> list : transposed) {
System.out.println(list);
}
System.out.println("---------------");
}
private static List<List<String>> transpose(List<List<String>> container) {
List<List<String>> newList = new ArrayList<List<String>>();
int max = getMax(container);
int i = 0;
for (List<String> list : container) {
for (int j = 0; j < max; j++) {
String string =j<list.size()?list.get(j):null;
setList(i, string, getList(newList, j));
}
i++;
}
return newList;
}
private static int getMax(List<List<String>> container) {
int max=0;
for (List<String> list : container) {
max = Math.max(list.size(), max);
}
return max;
}
private static void setList(int i, String string,
List<String> newInnerList) {
if (i >= newInnerList.size()) {
newInnerList.add(string);
} else {
newInnerList.set(i, string);
}
}
private static List<String> getList(List<List<String>> list, int j) {
List<String> innerList;
if (j >= list.size()) {
innerList = new ArrayList<String>();
list.add(innerList);
}else{
innerList = list.get(j);
}
return innerList;
}
输出
[list11, list12, list13]
[list21, list22]
[list31, list32, list33, list34]
---------------
[list11, list21, list31]
[list12, list22, list32]
[list13, null, list33]
[null, null, list34]
---------------