Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - transposing a list of list using streams

Tags:

java

list

stream

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.

like image 797
Julien BERNARD Avatar asked Jan 28 '23 10:01

Julien BERNARD


1 Answers

I like your question! Here's a simple way to achieve it, as long as the Lists 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.

like image 72
Jacob G. Avatar answered Feb 05 '23 08:02

Jacob G.