将LongStream划分为具有最大长度的子流 [英] Divide LongStream into substreams with maximal length

查看:428
本文介绍了将LongStream划分为具有最大长度的子流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有一些SQL语句包含带有给定ID的 IN -clauses。问题是在某些情况下可能会有超过1000个ID导致Oracle与ORA-01795崩溃。项目太多。

There are some SQL statements in my program that contain IN-clauses with given Ids. The problem is that in some cases there might be more than 1000 Ids which causes Oracle to crash with ORA-01795. Too many items.

所以我想把这个列表分成多个子列表。

So I want to divide this list into multiple sub-lists.

示例:I有2403个ID

Example: I have 2403 Ids

结果将是三个列表:


  1. 0 - 999

  2. 1000 - 1999

  3. 2000 - 2402

我写了一段有效的代码,但看起来很糟糕。有没有更好的解决方案来解决这个问题?可能与收藏家和收藏家有关groupingby或类似的东西?

I have written a piece of code that works, but looks terrible. Is there any better solution for this problem? Maybe something with Collectors & groupingby or anything like that?

我的代码:

    Map<Integer, List<Long>> result = new HashMap<>();
    ArrayList<Long> asList = new ArrayList<Long>(listOfIds);
    IntStream.range(0, (listOfIds.size() / 1000) + 1)
             .forEach(partGroup -> result.put(partGroup, asList.subList(partGroup * 1000, (partGroup * 1000) + Math.min(1000, 
             asList.size() - partGroup * 1000))));


推荐答案

如果不使用第三方库,我不会认为你可以做得更好。我个人使用这个实用功能,它接近你所做的:

Short of using a third party library I don't think you can do much better. I personally use this utility function, which is close to what you've done:

public static <T> Stream<List<T>> splitListStream(List<T> input, int batchSize) {
  if (batchSize <= 0)
    throw new IllegalArgumentException("batchSize must be positive (" + batchSize + ")");
  if (input.size() <= batchSize) return Stream.of(input);
  return IntStream.range(0, (input.size() + batchSize - 1) / batchSize)
          .mapToObj(i -> {
            int from = i * batchSize;
            int to = Math.min((i + 1) * batchSize, input.size());
            return input.subList(from, to);
          });
}

这篇关于将LongStream划分为具有最大长度的子流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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