Set<String> gatherTimeList = eSResponseList.stream() .map(DevPortReportEsDTO::getGatherTime) // 获取目标字段的值 .collect(Collectors.toSet()); // 转为列表 Map<String, DevPortReportEsDTO> reportEsDTOMap = new HashMap<>(); Map<String, List<PortReportResultVo>> relayLinkAndPortMap1 = new HashMap<>(); for (Map.Entry<String, List<TrDevportVO>> entry : relayLinkAndPortListMap.entrySet()) { String key = entry.getKey(); List<TrDevportVO> values = entry.getValue(); List<PortReportResultVo> resultVoList = new ArrayList<>(); for (String gatherTime : gatherTimeList) { for (TrDevportVO trDevportVO : values) { String tempKey = trDevportVO.getDevId() + trDevportVO.getPortName() + gatherTime; DevPortReportEsDTO reportEsDTO = reportEsDTOMap.get(tempKey); PortReportResultVo reportResultVo = new PortReportResultVo(); BeanUtil.copyProperties(trDevportVO, reportResultVo); reportResultVo.setPortBandwidth(trDevportVO.getBandwidth()); BeanUtil.copyProperties(reportEsDTO, reportResultVo); resultVoList.add(reportResultVo); } // key为链路组id+ 采集时间 relayLinkAndPortMap1.put(key + "@" + gatherTime, resultVoList); } } 优化一下这段代码
时间: 2024-02-14 19:04:16 浏览: 125
Java笔记word.docx
可以考虑将两个循环嵌套的部分使用 Stream 进行优化,减少循环次数,如下所示:
```
Map<String, List<PortReportResultVo>> relayLinkAndPortMap1 = relayLinkAndPortListMap.entrySet().stream()
.flatMap(entry -> gatherTimeList.stream()
.map(gatherTime -> {
String key = entry.getKey();
List<TrDevportVO> values = entry.getValue();
return values.stream()
.map(trDevportVO -> {
String tempKey = trDevportVO.getDevId() + trDevportVO.getPortName() + gatherTime;
DevPortReportEsDTO reportEsDTO = reportEsDTOMap.get(tempKey);
PortReportResultVo reportResultVo = new PortReportResultVo();
BeanUtil.copyProperties(trDevportVO, reportResultVo);
reportResultVo.setPortBandwidth(trDevportVO.getBandwidth());
BeanUtil.copyProperties(reportEsDTO, reportResultVo);
return reportResultVo;
})
.collect(Collectors.toList());
})
.map(resultVoList -> key + "@" + gatherTime, resultVoList))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
```
这样可以减少循环次数,提高代码效率。
阅读全文