如何将列表分配到子列表中,同时保持元素的原始顺序?

如何将列表分配到子列表中,同时保持元素的原始顺序?,第1张

如何将列表分配到子列表中,同时保持元素的原始顺序

如果源列表支持有效的随机访问,

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]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5616306.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存