我自己写了一个实用程序来将列表分成给定大小的批次。我只是想知道是否已经有任何apache commons util。
public static <T> List<List<T>> getBatches(List<T> collection,int batchSize){
int i = 0;
List<List<T>> batches = new ArrayList<List<T>>();
while(i<collection.size()){
int nextInc = Math.min(collection.size()-i,batchSize);
List<T> batch = collection.subList(i,i+nextInc);
batches.add(batch);
i = i + nextInc;
}
return batches;
}
如果已有相同的实用程序,请告诉我。
答案 0 :(得分:214)
从 Lists.partition(java.util.List, int)
查看Google Guava:
返回列表的连续子列表,每个列表具有相同的大小(最终列表可能更小)。例如,对包含
[a, b, c, d, e]
且分区大小为3的列表进行分区会产生[[a, b, c]
,[d, e]]
- 包含两个内部列表的外部列表,包含三个和两个元素,所有这些都按原始顺序排列
答案 1 :(得分:42)
如果您想生成Java-8批处理流,可以尝试以下代码:
public static <T> Stream<List<T>> batches(List<T> source, int length) {
if (length <= 0)
throw new IllegalArgumentException("length = " + length);
int size = source.size();
if (size <= 0)
return Stream.empty();
int fullChunks = (size - 1) / length;
return IntStream.range(0, fullChunks + 1).mapToObj(
n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
System.out.println("By 3:");
batches(list, 3).forEach(System.out::println);
System.out.println("By 4:");
batches(list, 4).forEach(System.out::println);
}
输出:
By 3:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10, 11, 12]
[13, 14]
By 4:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14]
答案 2 :(得分:12)
另一种方法是使用Collectors.groupingBy
索引,然后将分组索引映射到实际元素:
final List<Integer> numbers = range(1, 12)
.boxed()
.collect(toList());
System.out.println(numbers);
final List<List<Integer>> groups = range(0, numbers.size())
.boxed()
.collect(groupingBy(index -> index / 4))
.values()
.stream()
.map(indices -> indices
.stream()
.map(numbers::get)
.collect(toList()))
.collect(toList());
System.out.println(groups);
输出:
[1,2,3,4,5,6,7,8,9,10,11]
[[1,2,3,4],[5,6,7,8],[9,10,11]]
答案 3 :(得分:6)
我想出了这个:
private static <T> List<List<T>> partition(Collection<T> members, int maxSize)
{
List<List<T>> res = new ArrayList<>();
List<T> internal = new ArrayList<>();
for (T member : members)
{
internal.add(member);
if (internal.size() == maxSize)
{
res.add(internal);
internal = new ArrayList<>();
}
}
if (internal.isEmpty() == false)
{
res.add(internal);
}
return res;
}
答案 4 :(得分:5)
以下示例演示了List的分块:
package de.thomasdarimont.labs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SplitIntoChunks {
public static void main(String[] args) {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
List<List<Integer>> chunks = chunk(ints, 4);
System.out.printf("Ints: %s%n", ints);
System.out.printf("Chunks: %s%n", chunks);
}
public static <T> List<List<T>> chunk(List<T> input, int chunkSize) {
int inputSize = input.size();
int chunkCount = (int) Math.ceil(inputSize / (double) chunkSize);
Map<Integer, List<T>> map = new HashMap<>(chunkCount);
List<List<T>> chunks = new ArrayList<>(chunkCount);
for (int i = 0; i < inputSize; i++) {
map.computeIfAbsent(i / chunkSize, (ignore) -> {
List<T> chunk = new ArrayList<>();
chunks.add(chunk);
return chunk;
}).add(input.get(i));
}
return chunks;
}
}
输出:
Ints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Chunks: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]
答案 5 :(得分:1)
List<T> batch = collection.subList(i,i+nextInc);
->
List<T> batch = collection.subList(i, i = i + nextInc);
答案 6 :(得分:1)
这里有个例子:
final AtomicInteger counter = new AtomicInteger();
final int partitionSize=3;
final List<Object> list=new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
final Collection<List<Object>> subLists=list.stream().collect(Collectors.groupingBy
(it->counter.getAndIncrement() / partitionSize))
.values();
System.out.println(subLists);
输入: [A,B,C,D,E]
输出: [[A,B,C],[D,E]]
您可以在此处找到示例: https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/
答案 7 :(得分:1)
类似于OP,没有流和库,但简洁:
public <T> List<List<T>> getBatches(List<T> collection, int batchSize) {
List<List<T>> batches = new ArrayList<>();
for (int i = 0; i < collection.size(); i += batchSize) {
batches.add(collection.subList(i, Math.min(i + batchSize, collection.size())));
}
return batches;
}
答案 8 :(得分:1)
使用Apache Commons ListUtils.partition。
答案 9 :(得分:1)
在Java 9中,可以在hasNext
条件下使用IntStream.iterate()
。因此,您可以将方法的代码简化为:
public static <T> List<List<T>> getBatches(List<T> collection, int batchSize) {
return IntStream.iterate(0, i -> i < collection.size(), i -> i + batchSize)
.mapToObj(i -> collection.subList(i, Math.min(i + batchSize, collection.size())))
.collect(Collectors.toList());
}
使用{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
,getBatches(numbers, 4)
的结果将是:
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
答案 10 :(得分:1)
曾经有another question被关闭,因为它是与此书的复制品,但是如果您仔细阅读,它的确会有所不同。因此,如果有人(例如我)实际上想要将列表拆分为给定数量的几乎相等大小的子列表,然后继续阅读。
我只是将here中描述的算法移植到Java。
@Test
public void shouldPartitionListIntoAlmostEquallySizedSublists() {
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
int numberOfPartitions = 3;
List<List<String>> split = IntStream.range(0, numberOfPartitions).boxed()
.map(i -> list.subList(
partitionOffset(list.size(), numberOfPartitions, i),
partitionOffset(list.size(), numberOfPartitions, i + 1)))
.collect(toList());
assertThat(split, hasSize(numberOfPartitions));
assertEquals(list.size(), split.stream().flatMap(Collection::stream).count());
assertThat(split, hasItems(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g")));
}
private static int partitionOffset(int length, int numberOfPartitions, int partitionIndex) {
return partitionIndex * (length / numberOfPartitions) + Math.min(partitionIndex, length % numberOfPartitions);
}
答案 11 :(得分:0)
import com.google.common.collect.Lists;
List<List<T>> batches = Lists.partition(List<T>,batchSize)
使用Lists.partition(List,batchSize)。您需要从Google通用软件包(Lists
)导入com.google.common.collect.Lists
它将返回List<T>
的列表,且每个元素的大小等于您的batchSize
。
答案 12 :(得分:0)
Java 8的单行代码是:
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.*;
private static <T> Collection<List<T>> partition(List<T> xs, int size) {
return IntStream.range(0, xs.size())
.boxed()
.collect(collectingAndThen(toMap(identity(), xs::get), Map::entrySet))
.stream()
.collect(groupingBy(x -> x.getKey() / size, mapping(Map.Entry::getValue, toList())))
.values();
}
答案 13 :(得分:0)
这是Java 8+的简单解决方案:
public static <T> Collection<List<T>> prepareChunks(List<T> inputList, int chunkSize) {
AtomicInteger counter = new AtomicInteger();
return inputList.stream().collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize)).values();
}
答案 14 :(得分:0)
您可以使用下面的代码来获取列表的批次。
Iterable<List<T>> batchIds = Iterables.partition(list, batchSize);
您需要导入Google Guava库才能使用上述代码。
答案 15 :(得分:0)
解决此问题的另一种方法:
public class CollectionUtils {
/**
* Splits the collection into lists with given batch size
* @param collection to split in to batches
* @param batchsize size of the batch
* @param <T> it maintains the input type to output type
* @return nested list
*/
public static <T> List<List<T>> makeBatch(Collection<T> collection, int batchsize) {
List<List<T>> totalArrayList = new ArrayList<>();
List<T> tempItems = new ArrayList<>();
Iterator<T> iterator = collection.iterator();
for (int i = 0; i < collection.size(); i++) {
tempItems.add(iterator.next());
if ((i+1) % batchsize == 0) {
totalArrayList.add(tempItems);
tempItems = new ArrayList<>();
}
}
if (tempItems.size() > 0) {
totalArrayList.add(tempItems);
}
return totalArrayList;
}
}
答案 16 :(得分:0)
请注意,List#subList()
返回基础集合的副本,这在编辑较小的列表时可能会导致意外后果 - 编辑将反映在原始集合中或可能引发 ConcurrentModificationException