是否有一个通用的Java实用程序来将列表分成批处理? [英] Is there a common Java utility to break a list into batches?
问题描述
我自己写了一个实用程序来将列表分成给定大小的批次。我只是想知道是否已经有任何apache commons util。
I wrote myself a utility to break a list into batches of given size. I just wanted to know if there is already any apache commons util for this.
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;
}
如果已有相同的实用工具,请告诉我。
Please let me know if there any existing utility already for the same.
推荐答案
查看 Lists.partition(java.util.List,int)来自 Google Guava 的code>
:
Check out Lists.partition(java.util.List, int)
from Google Guava:
返回列表的连续子列表,每个列表大小相同(最终列表可能更小)。例如,使用分区大小为3对包含
[a,b,c,d,e]
的列表进行分区会产生[[a,b, c]
,[d,e]]
- 一个外部列表,包含两个内部列表,包含三个和两个元素,全部按原始顺序排列。
Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing
[a, b, c, d, e]
with a partition size of 3 yields[[a, b, c]
,[d, e]]
-- an outer list containing two inner lists of three and two elements, all in the original order.
这篇关于是否有一个通用的Java实用程序来将列表分成批处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!