通用util将列表分成批 [英] Common util to break a list into batch

查看:141
本文介绍了通用util将列表分成批的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我自己写了一个工具,将一个列表分成给定大小的批次。我只想知道这是否已经有任何apache commons util。

I wrote myself a util 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;
}

请让我知道, p>

Please let me know if there any existing util already for the same.

推荐答案

查看 Lists.partition(java.util.List,int) 来自 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.

这篇关于通用util将列表分成批的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆