我希望将一个列表均匀地分成指定数量的子列表。例如,我有一个包含1到10个元素的列表,我想要3个子列表。它们应该如下所示:
SL1 -> {1, 2, 3, 4}
SL2 -> {5, 6, 7}
SL3 -> {8, 9, 10}
重要提示: 每个列表包含的内容不重要,例如 SL1 可以包含 {1, 5, 7, 10}。最重要的是有两个大小为3的列表和一个大小为4的列表。
我尝试了几种方法,包括使用 Iterables.partition
,但这并没有帮助。
我唯一想到可行的方法是:
public Iterable<List<Integer>> distributeEvenlyQueryListIntoLists(final LinkedList<Integer> bigList, final Integer numberOfSublists) {
List<List<Integer>> result = new ArrayList<>();
// Creates as many lists as needed
for (int i = 0; i < numberOfSublists; i++) {
result.add(new ArrayList<>());
}
while (bigList.iterator().hasNext()) {
for (int i = 0; i < numberOfSublists; i++) {
if (!bigList.iterator().hasNext()) {
break;
}
result.get(i).add(bigList.poll());
}
}
return result;
}
传递的 bigList
不必是一个 LinkedList
,它可以是任何 Iterable
。
我特别讨厌第一个循环,因为我需要创建子列表。
谢谢!
Stream.of(ArrayList::new, i->ArrayList::new).limit(partitions).collect(Collectors.toList())
,但这种方法有点hackish。我脑海中刚想到的另一种替代方法是将输入限制为类型List<T>
并使用subList
,这将创建原始列表的视图。 - user4668606