如何将列表拆分为给定数量的列表,按顺序获取元素并将它们分配到子列表(因此不对列表进行分区)?
我想尽可能“好”地做到这一点(使用 Java 8 功能或 Guava 或类似的东西。
- 示例列表:
[1 2 3 4 5 6 7]
- 应分为 3 部分:
[1 4 7]
[2 5]
[3 6]
- 应分为 2 部分:
[1 3 5 7]
[2 4 6]
最佳答案
如果源列表支持高效的随机访问,如ArrayList
,则可以使用
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]
关于java - 如何将列表分配为子列表,同时保持元素的原始顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900141/