是否有通用的 Java 实用程序可以将列表分解为批?

2022-08-31 06:07:59

我给自己写了一个实用程序,将列表分解成给定大小的批次。我只是想知道是否已经有任何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;
}

如果已经有任何现有的实用程序,请让我知道。


答案 1

查看Lists.partition(java.util.List,int)Google Guava

返回列表的连续子列表,每个子列表的大小相同(最终列表可能更小)。例如,对包含分区大小为 3 的列表进行分区,将得到 -- 一个包含三个元素和两个元素的两个内部列表的外部列表,全部按原始顺序排列。[a, b, c, d, e][[a, b, c][d, e]]


答案 2

如果要生成 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]