如何迭代大列表以使其较小,以便使用Java流进行REST调用?

问题描述 投票:0回答:2

我有类似这样的逻辑要分块处理。

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流进行此迭代的更好方法?

java stream java-stream
2个回答
0
投票

您可以使用apache commons中的ListUtils进行拆分(如果您确实需要,因为1000并不是那么多)

List<List<Integer>> output = ListUtils.partition(largeList, targetSize);

0
投票

您可以将处理分批处理成固定大小的卡盘(或更高级地动态计算批处理大小)。

 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)

© www.soinside.com 2019 - 2024. All rights reserved.