gpt4 book ai didi

java - 将列表均匀分布到 Java 中的子列表中

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:18 28 4
gpt4 key购买 nike

我想将一个列表平均分配到给定数量的子列表中。例如,我有一个包含元素 1 到 10 的列表,我想要 3 个列表。这些应该看起来像:

SL1 -> {1, 2, 3, 4}
SL2 -> {5, 6, 7}
SL3 -> {8, 9, 10}

重要:每个列表包含的内容是不相关的,即 SL1 可能有 {1, 5, 7, 10}。最重要的是,有 2 个大小为 3 的列表和 1 个大小为 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

我特别讨厌创建子列表的第一个循环。

谢谢!

最佳答案

只需以循环模式分发它们:

public <T> List<List<T>> partition(Iterable<T> iterable, int partitions){
List<List<T>> result = new ArrayList<>(partitions);
for(int i = 0; i < partitions; i++)
result.add(new ArrayList<>());

Iterator<T> iterator = iterable.iterator()
for(int i = 0; iterator.hasNext(); i++)
result.get(i % partitions).add(iterator.next());

return result;
}

使用此代码运行示例:

List<String> l = Stream.iterate(0, i->i + 1).limit(25).map(i->Integer.toString(i)).collect(Collectors.toList());
System.out.println(partition(l, 4).toString());

生产

[[0, 4, 8, 12, 16, 20, 24], [1, 5, 9, 13, 17, 21], [2, 6, 10, 14, 18, 22], [3, 7, 11, 15, 19, 23]]

基本思想是将单个元素添加到结果集中的每个列表中。这样可以保证两个列表的元素个数之差不超过1。

作为替代方案,您可以使用 Iterables.partition 的 Guava 实现,它采用了一种略有不同的方法。

关于java - 将列表均匀分布到 Java 中的子列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41287770/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com