问题描述
现在我想将列转换为行,例如以下示例: 有一些列表:
List1: {"1","2","3"}
List2: {"1","3","4"}
List3: {"1","4","5"}
然后我想将它们转换为:
ListA: {"1","1","1"}
ListB: {"2","2"}
ListC: {"3","3"}
ListD: {"","4"}
ListE: {"","","5"}
以下是我的解决方案:
List<List<String>> list = Lists.newArrayList(
Lists.newArrayList("1","5"),Lists.newArrayList("1","4"),"3"));
List<List<String>> res = Lists.newArrayList();
TreeMap<Integer,List<String>> map = list.stream().collect(Collectors.toMap(List::size,Function.identity(),(b1,b2) -> b1,TreeMap::new));
int size = map.get(map.lastKey()).size();
for (int i = 0; i < size; i++) {
int finalI = i;
res.add(list.stream().map(list1 -> {
if (list1.size() > finalI) {
return list1.get(finalI);
}
return "";
}).collect(Collectors.toList()));
}
但是它的复杂度是 O(n²),还有其他更好的解决方案吗?
解决方法
public static void main(String[] args) {
// Create input list
List<String> list1 = List.of("1","2","3");
List<String> list2 = List.of("1","3","4");
List<String> list3 = List.of("1","4","5");
// Create ouput list
List<List<String>> outputList = new ArrayList<>();
// Iterate for max length of lists
IntStream
.range(0,getMax(list1,list2,list3))
.forEach(index -> {
outputList.add(
Arrays.asList(getElementByIndexOrEmpty(list1,index),getElementByIndexOrEmpty(list2,getElementByIndexOrEmpty(list3,index))
);
});
System.out.println(outputList);
}
// Return element at index if present else return empty string
private static String getElementByIndexOrEmpty(List<String> list,int index) {
return list.size() > index ? list.get(index) : "";
}
// Find max length of lists
private static int getMax(List<String> list1,List<String> list2,List<String> list3) {
return Math.max(list1.size(),Math.max(list2.size(),list3.size()));
}
代码只遍历所有列表一次(对于任何列表的最大长度)。