How to transpose List?

前端 未结 10 718
温柔的废话
温柔的废话 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:43

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

    public static  List> transpose(List> list) {
       final int N = list.stream().mapToInt(l -> l.size()).max().orElse(-1);
       List> 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());
    }
    

提交回复
热议问题