问题描述
出于改进目的,我正尝试仅使用流来转置列表列表.
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
以下堆栈溢出问题中提供了一种迭代方法:如何转置List< List> ?
An iterative way is provided in the following Stack Overflow question : How to transpose List<List>?
到目前为止,我只想到了丑陋的解决方案,例如将Double替换为包含列表中的值和索引的自定义对象,使用flatMap进行展平,再使用groupBy使用保存的索引再次构建它,然后转到回到双打.
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.
推荐答案
我喜欢你的问题!只要List
是正方形(每个List
包含相同数量的元素),这是一种简单的实现方法:
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.
这篇关于Java-使用流转换列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!