如何将列表分发到子列表中,保持元素的原始顺序? [英] How to distribute a list into sub-lists, keeping the original order of the elements?
本文介绍了如何将列表分发到子列表中,保持元素的原始顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将列表拆分为给定数量的列表,按顺序获取元素并将它们分发到子列表(所以不对列表进行分区)?
How to split a list into a given number of lists, taking the elements in order and distributing them to the sub-lists (so not partitioning the list)?
我想尽可能好(使用Java 8功能或Guava或类似的东西。)
I would like to do this as "nice" as possible (using Java 8 features or Guava or something similar.
- 示例列表:
[1 2 3 4 5 6 7]
- 应分为3:
[1 4 7]
[2 5]
[3 6]
- 应分为2:
[1 3 5 7]
[2 4 6]
- Example list:
[1 2 3 4 5 6 7]
- Should be split in 3 :
[1 4 7]
[2 5]
[3 6]
- Should be split in 2 :
[1 3 5 7]
[2 4 6]
推荐答案
如果源列表支持有效的随机访问,例如 ArrayList
是的,你可以使用
If the source list supports efficient random access, like ArrayList
does, you can use
IntStream.range(0, source.size()).boxed()
.collect(groupingBy(i->i%listCount, LinkedHashMap::new, mapping(source::get, toList())));
例如
List<Integer> source=IntStream.range(0, 20).boxed().collect(toList());
System.out.println(source);
int listCount=5;
Map<Integer, List<Integer>> collect = IntStream.range(0, source.size()).boxed()
.collect(groupingBy(i->i%listCount, LinkedHashMap::new, mapping(source::get, toList())));
// in case it really has to be a List:
List<List<Integer>> result=new ArrayList<>(collect.values());
result.forEach(System.out::println);
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 5, 10, 15]
[1, 6, 11, 16]
[2, 7, 12, 17]
[3, 8, 13, 18]
[4, 9, 14, 19]
这篇关于如何将列表分发到子列表中,保持元素的原始顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文