微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java 将列切换为行

如何解决Java 将列切换为行

现在我想将列转换为行,例如以下示例: 有一些列表:

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()));
}

代码只遍历所有列表一次(对于任何列表的最大长度)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?