List<List<ZeekrFriend>> collect1 = zeekrFriendsMap.entrySet().stream().filter(entry -> collect.contains(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); List<ZeekrFriend> collect2 = collect1.stream() .flatMap(List::stream) .collect(Collectors.toList());优化这段代码
时间: 2024-03-05 22:49:27 浏览: 139
可以将两个流操作合并为一个,这样可以避免创建中间集合,提高代码的效率。示例代码如下:
List<ZeekrFriend> flattenedList = zeekrFriendsMap.entrySet().stream()
.filter(entry -> collect.contains(entry.getKey()))
.flatMap(entry -> entry.getValue().stream())
.collect(Collectors.toList());
这样就可以将原来的两个流操作合并为一个,将Map中符合条件的value打平成一个List
相关问题
List<String> collect = Arrays.stream(item.getDivideTo().split("\\|")) .collect(Collectors.toList()); List<ZeekrFriend> flattenedList = zeekrFriendsMap.entrySet().stream() .filter(entry -> collect.contains(entry.getKey())) .flatMap(entry -> entry.getValue().stream()) .collect(Collectors.toList()); item.setFriends(flattenedList);优化这段代码
可以使用方法引用来进一步简化代码,同时对stream的调用进行优化,示例代码如下:
List<ZeekrFriend> flattenedList = Arrays.stream(item.getDivideTo().split("\\|"))
.flatMap(key -> zeekrFriendsMap.getOrDefault(key, Collections.emptyList()).stream())
.collect(Collectors.toList());
item.setFriends(flattenedList);
这样的代码更加简洁,同时通过使用getOrDefault方法来避免了对Map中可能不存在的key进行空指针判断,提高了代码的健壮性。
优化这段代码:Map<String, List<DeepAnalysisSmsRecordResultVo>> smsListMap = smsList.stream().collect(Collectors.groupingBy(DeepAnalysisSmsRecordResultVo::getCollectTargetId)); for (Map.Entry<String, List<DeepAnalysisSmsRecordResultVo>> entry : smsListMap.entrySet()) { String key = entry.getKey(); List<DeepAnalysisSmsRecordResultVo> value = entry.getValue(); if (key.contains(iNode.getCollectTargetId())) { Integer z = null; for (DeepAnalysisSmsRecordResultVo sms : value) { String phone = sms.getOtherNumber(); List<MobilePhonePersonIdentityNumberVo> persons = getCasePerson("3", phone); Long personId = persons.get(0).getPersonId(); for (int j = 0; j < nodeList.size(); j++) { MobilePhoneModelPersonDiagramNodeVo jNode = nodeList.get(j); if (jNode.getPersonId().equals(personId)) { z = j; break; } } } MobilePhoneModelPersonDiagramLinkVo linkVo = new MobilePhoneModelPersonDiagramLinkVo(); linkVo.setSource(i); linkVo.setTarget(z); linkVo.setName("短信记录"); linkVo.setNumber(value.size()); linkList.add(linkVo); } }
优化后的代码如下:
Map<String, List
for (Map.Entry<String, List
for (DeepAnalysisSmsRecordResultVo sms : value) {
String phone = sms.getOtherNumber();
List<MobilePhonePersonIdentityNumberVo> persons = getCasePerson("3", phone);
Long personId = persons.get(0).getPersonId();
for (int j = 0; j < nodeList.size(); j++) {
MobilePhoneModelPersonDiagramNodeVo jNode = nodeList.get(j);
if (jNode.getPersonId().equals(personId)) {
z = j;
break;
}
}
}
MobilePhoneModelPersonDiagramLinkVo linkVo = new MobilePhoneModelPersonDiagramLinkVo();
linkVo.setSource(i);
linkVo.setTarget(z);
linkVo.setName("短信记录");
linkVo.setNumber(value.size());
linkList.add(linkVo);
}
相关推荐
















