再精简优化下这个段代码 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 16:19:21 浏览: 21
可以将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表达式。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)