题设: 有n个list 长度不一,现在要将这n个list中下标相同生成一个新的list,如果对应下表无值(越界)则默认为空,应该怎么做(除了遍历最长的list去手动操作以外)?
实例:
list1:{"1","2","3"},
list2:{"1","2","3","4"}
list3:{"1","2","3","4","5"}
结果:
listA:{"1","1","1"}
listB:{"2","2","2"}
listC:{"3","3","3"}
listD:{"","4","4"}
listE:{"","","5"}
以下是我的做法,但是时间复杂度是O(n²)
List<List<String>> list = Lists.newArrayList(
Lists.newArrayList("1", "2", "3", "4", "5"),
Lists.newArrayList("1", "2", "3", "4"),
Lists.newArrayList("1", "2", "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()));
}
System.out.println(JacksonUtil.toSerialize(res));
我只想说,Java 代码真不好耍