我的程序中有一些SQL语句包含IN给定ID的-clauses.问题是在某些情况下可能会有超过1000个ID导致Oracle与ORA-01795崩溃.过多的物品.
所以我想把这个列表分成多个子列表.
示例:我有2403个ID
结果将是三个列表:
我写了一段有用的代码,但看起来很糟糕.有没有更好的解决方案来解决这个问题?也许与收藏家和分组或其他类似的东西?
我的代码:
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))));
Run Code Online (Sandbox Code Playgroud)
如果没有使用第三方库,我认为你不能做得更好.我个人使用这个实用功能,这与你所做的很接近:
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);
});
}
Run Code Online (Sandbox Code Playgroud)