优化这段代码:List<CompletableFuture<Map<String, Object>>> futureList = new ArrayList<>(); for (PersonBasicVo person : personList) { CompletableFuture<Map<String, Object>> future = CompletableFuture.supplyAsync(() -> { String personNo = person.getPersonNo(); List<ContactsBasic> contactsList = contactsService.list(Wrappers.lambdaQuery(ContactsBasic.class) .eq(ContactsBasic::getPersonNo, personNo) .ne(ContactsBasic::getRelationshipAccount, "") .isNotNull(ContactsBasic::getPersonNo) .like(StrUtil.isNotBlank(phone), ContactsBasic::getRelationshipAccount, phone)); if (CollUtil.isNotEmpty(contactsList)) { Map<String, Object> contactsMap = new HashMap<>(); contactsMap.put("personNo", personNo); contactsMap.put("contactsList", contactsList); return contactsMap; } else { return null; } }, executor); futureList.add(future); } List<Map<String, Object>> contactsMapList = futureList.stream() .map(CompletableFuture::join) .filter(Objects::nonNull) .collect(Collectors.toList());
时间: 2024-02-14 17:27:21 浏览: 100
优化后的代码如下:
```java
List<CompletableFuture<Map<String, Object>>> futureList = personList.stream()
.map(person -> CompletableFuture.supplyAsync(() -> {
String personNo = person.getPersonNo();
List<ContactsBasic> contactsList = contactsService.list(Wrappers.lambdaQuery(ContactsBasic.class)
.eq(ContactsBasic::getPersonNo, personNo)
.ne(ContactsBasic::getRelationshipAccount, "")
.isNotNull(ContactsBasic::getPersonNo)
.like(StrUtil.isNotBlank(phone), ContactsBasic::getRelationshipAccount, phone));
if (CollUtil.isNotEmpty(contactsList)) {
Map<String, Object> contactsMap = new HashMap<>();
contactsMap.put("personNo", personNo);
contactsMap.put("contactsList", contactsList);
return contactsMap;
} else {
return null;
}
}, executor))
.collect(Collectors.toList());
List<Map<String, Object>> contactsMapList = futureList.stream()
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toList());
```
主要优化:
1. 使用流式编程,替换原来的for循环。
2. 使用`stream()`和`collect(Collectors.toList())`方法来收集结果,代替手动添加到列表中。
3. 将lambda表达式内联,使代码更简洁。
阅读全文