How to transpose List?

前端 未结 10 721
温柔的废话
温柔的废话 2021-01-01 17:59

I have a following ArrayList,

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

And I would like to convert this one like this,



        
相关标签:
10条回答
  • 2021-01-01 18:39

    The mathematics behind: you need to transpose the matrix. It's easier if you use a 2-dimensional array or a 'List of Lists', which is pretty much he same with collections. A List of arrays works too, but it is slightly more confusing.

    This wikipedia article shows some algorithms for transposition.

    0 讨论(0)
  • 2021-01-01 18:40

    The technique is called transposing. Example of an implementation.

    public static MyObject [][] transpose(MyObject [][] m){
        int r = m.length;
        int c = m[r].length;
        MyObject [][] t = new MyObject[c][r];
        for(int i = 0; i < r; ++i){
            for(int j = 0; j < c; ++j){
                t[j][i] = m[i][j];
            }
        }
        return t;
    }
    
    0 讨论(0)
  • 2021-01-01 18:43

    Here is my solution.Thanks to @jpaugh's code.I hope this will help you.^_^

    public static <T> List<List<T>> transpose(List<List<T>> list) {
       final int N = list.stream().mapToInt(l -> l.size()).max().orElse(-1);
       List<Iterator<T>> iterList = list.stream().map(it->it.iterator()).collect(Collectors.toList());
       return IntStream.range(0, N)
           .mapToObj(n -> iterList.stream()
           .filter(it -> it.hasNext())
           .map(m -> m.next())
           .collect(Collectors.toList()))
       .collect(Collectors.toList());
    }
    
    0 讨论(0)
  • 2021-01-01 18:44

    This called a transpose operation. A code sample is here, , but will need significant modification as you have an ArrayList of Arrays (what I infer from your question)

    0 讨论(0)
  • 2021-01-01 18:46

    something like this maybe

    List<List<String>> list = new ArrayList<List<String>>(firstList.size());
    for(int i = 0; i < firstList.size(); i++) {
       list.add(Arrays.asList(
          firstList.get(i),
          secondList.get(i),
          thirdList.get(i))
       );
    }
    
    0 讨论(0)
  • 2021-01-01 18:48

    If it is for a datamigration task, you might consider your friendly spreadsheet if the size is not too big.

    For matrix manipulation stuff there is the jScience library which has matrix support. For just transposing a metrix this would be overkill, but it depends what needs to be done with it.

    0 讨论(0)
提交回复
热议问题