本文介绍了如何使用Java流对大列表进行迭代以使其较小,以便进行REST调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类似的逻辑可以分块处理.
I have logic something like this to process in chunks.
List<String> bigList = getList(); // Returns a big list of 1000 recs
int startIndex=0;
boolean entireListNotProcessed=false;
while(entireListNotProcessed) {
int endIndex = startIndex + 100;
if(endIndex > myList.size()-1) {
endIndex=myList.size()-1;
}
List<String> subList= bigList.subList(startIndex, endIndex);
//call Rest API with subList and update entireListNotProcessed flag...
}
是否有使用Java流进行此迭代的更好方法?
Is there a better way of doing this iteration using java streams?
推荐答案
您可以通过此答案来执行类似的操作逐步创建范围,然后按subList
:
You can do similar to this answer, by creating range with stepping and then subList
:
int step = 100;
IntStream
.iterate(0, o -> o < bigList.size(), o -> o + step)
.mapToObj(i -> bigList.subList(i, Math.min(i + step, bigList.size()))
.forEach(subList -> callRestApi(subList));
或者您可以提取方法:
private static <T> Stream<List<T>> partition(List<T> list, int step) {
return IntStream
.iterate(0, o -> o < list.size(), o -> o + step)
.mapToObj(i -> list
.subList(i, Math.min(i + step, list.size()))
);
}
然后
partition(bigList, 100).forEach(subList -> callRestApi(subList));
这篇关于如何使用Java流对大列表进行迭代以使其较小,以便进行REST调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!