Java8实现列转行

题设: 有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));
阅读 5.8k
1 个回答

我只想说,Java 代码真不好耍

package jamesfan.playground.java.sf;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Transform {
    public static void main(String[] args) {
        List<List<String>> data = Stream.of(
            Stream.of("1", "2", "3").collect(Collectors.toList()),
            Stream.of("1", "2", "3", "4", "5").collect(Collectors.toList()),
            Stream.of("1", "2", "3", "7").collect(Collectors.toList())
        ).collect(Collectors.toList());

        int length = data.stream().mapToInt(a -> a.size()).max().orElse(0);

        List<List<String>> result = IntStream.range(0, length).mapToObj(i -> {
            return data.stream().map(a -> a.size() > i ? a.get(i) : null).collect(Collectors.toList());
        }).collect(Collectors.toList());

        result.forEach(one -> {
            one.forEach(s -> System.out.printf("%7s", s));
            System.out.println();
        });
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏