我有类似这样的逻辑要分块处理。
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流进行此迭代的更好方法?
您可以使用apache commons中的ListUtils进行拆分(如果您确实需要,因为1000并不是那么多)
List<List<Integer>> output = ListUtils.partition(largeList, targetSize);
您可以将处理分批处理成固定大小的卡盘(或更高级地动态计算批处理大小)。
final List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,); // any range of items.
final int batchSize = 3;
final AtomicInteger counter = new AtomicInteger();
final Collection<List<Integer>> result = numbers.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / batchSize))
.values();
您现在每个都有List
个元素的N
的集合(N = 3)