再精简优化下这个段代码 int batchCount = 500; int dataSizePerThread = Math.max(1, awardIds.size() / batchCount); List<CompletableFuture<List<TCaAwardInfo>>> futures = new ArrayList<>(); for (int i = 0; i < dataSizePerThread; i++) { int startIndex = i * batchCount; int endIndex = Math.min((i + 1) * batchCount, awardIds.size()); List<Long> subList = awardIds.subList(startIndex, endIndex); CompletableFuture<List<TCaAwardInfo>> future = CompletableFuture.supplyAsync(() -> { List<TCaAwardInfo> result = new ArrayList<>(); result = awardApiService.queryActivationCode(subList); return result; }, taskExecutor); futures.add(future); } List<TCaAwardInfo> activationCodeList = futures.stream() .flatMap(future -> future.join().stream()) .collect(Collectors.toList());
时间: 2024-04-28 19:19:21 浏览: 140
基于Springboot和Vue的精简博客系统源码 精简博客系统代码(高分项目源码)
可以将for循环中的部分代码提取出来,简化代码如下:
int batchCount = 500;
int dataSizePerThread = Math.max(1, awardIds.size() / batchCount);
List<CompletableFuture<List<TCaAwardInfo>>> futures = new ArrayList<>();
for (int i = 0; i < dataSizePerThread; i++) {
int startIndex = i * batchCount;
int endIndex = Math.min((i + 1) * batchCount, awardIds.size());
List<Long> subList = awardIds.subList(startIndex, endIndex);
CompletableFuture<List<TCaAwardInfo>> future = CompletableFuture.supplyAsync(() -> awardApiService.queryActivationCode(subList), taskExecutor);
futures.add(future);
}
List<TCaAwardInfo> activationCodeList = futures.stream()
.flatMap(CompletableFuture::join)
.collect(Collectors.toList());
这里简化了supplyAsync方法中的Lambda表达式,将返回值直接作为Lambda表达式的返回值,避免了创建ArrayList对象。同时使用方法引用的方式替换了flatMap中的Lambda表达式。
阅读全文