本文介绍了如何转置List< List>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下的ArrayList,

I have a following ArrayList,

[Title,Data1,Data2,Data3]
[A,2,3,4]
[B,3,5,7]
[Title,A,B]
[Data1,2,3]
[Data2,3,5]
[Data3,4,7]

我有点困惑的方法。非常感谢任何提示。

I'm bit confused with the approach. Any hint would be much appreciated.

感谢。

推荐答案

称为转置。以下代码段可以满足您的需要:

This is called transposition. The following snippet does what you need:

import java.util.*;
public class ListTranspose {
    public static void main(String[] args) {
        Object[][] data = {
            { "Title", "Data1", "Data2", "Data3" },
            { "A", 2, 3, 4 },
            { "B", 3, 5, 7 },
        };
        List<List<Object>> table = new ArrayList<List<Object>>();
        for (Object[] row : data) {
            table.add(Arrays.asList(row));
        }
        System.out.println(table); //  [[Title, Data1, Data2, Data3],
                                   //   [A, 2, 3, 4],
                                   //   [B, 3, 5, 7]]"
        table = transpose(table);
        System.out.println(table); //  [[Title, A, B],
                                   //   [Data1, 2, 3],
                                   //   [Data2, 3, 5],
                                   //   [Data3, 4, 7]]
    }
    static <T> List<List<T>> transpose(List<List<T>> table) {
        List<List<T>> ret = new ArrayList<List<T>>();
        final int N = table.get(0).size();
        for (int i = 0; i < N; i++) {
            List<T> col = new ArrayList<T>();
            for (List<T> row : table) {
                col.add(row.get(i));
            }
            ret.add(col);
        }
        return ret;
    }
}



另请参阅





  • See also

    • Wikipedia/Transpose
    • 这篇关于如何转置List&lt; List&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 02:49