是否有一个通用的 Java 实用程序可以将列表分成批次? [英] Is there a common Java utility to break a list into batches?

查看:25
本文介绍了是否有一个通用的 Java 实用程序可以将列表分成批次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我自己编写了一个实用程序,可以将列表分成给定大小的批次.我只是想知道是否已经有任何用于此的 apache commons 实用程序.

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) 来自 谷歌番石榴:

返回一个列表的连续子列表,每个子列表的大小相同(最终列表可能更小).例如,对包含 [a, b, c, d, e] 的列表进行分区,分区大小为 3,结果 [[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屋!

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