是否有一个通用的 Java 实用程序可以将列表分成多个批次?

新手上路,请多包涵

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

请让我知道是否已经有任何现有的实用程序。

原文由 Harish 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 671
2 个回答

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

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

原文由 Tomasz Nurkiewicz 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 Tagir Valeev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题