For improvement purposes, I am trying to use exclusively streams to transpose a list of list.
By that I mean, that I have a List of List of Doubles that contains for example
1 2 3 4
5 6 7 8
And I would like to obtain a List of List of Doubles that contains
1 5
2 6
3 7
4 8
An iterative way is provided in the following Stack Overflow question : How to transpose List<List>?
I have only thought of ugly solutions so far, such as replacing the Double with a custom object that holds the value and the index in the list, flatten using flatMap, build it again using groupBy with the index I saved and then go back to Doubles.
Please let me know if you are aware of any clean way. Thanks.
I like your question! Here's a simple way to achieve it, as long as the List
s are square (every List
contains the same number of elements):
List<List<Integer>> list = List.of(List.of(1, 2, 3, 4), List.of(5, 6, 7, 8));
IntStream.range(0, list.get(0).size())
.mapToObj(i -> list.stream().map(l -> l.get(i)).collect(Collectors.toList()))
.collect(Collectors.toList());
The above code returns the following:
[[1, 5], [2, 6], [3, 7], [4, 8]]
Note: This will not perform well for large lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With