怎么将for里面的代码提取出来 有什么好的方式
List list = apiServiceResponseDTOIPage.getRecords();
if (CollectionUtils.isNotEmpty(list)) {
for (ApiServiceResponseDTO apiServiceResponseDTO : list) {
String libraryId = apiServiceResponseDTO.getLibraryId();
if (StringUtils.isNotBlank(libraryId)) {
LabelLibraryInfoPO labelLibraryInfoPO = labelLibrayInfoMapper.selectById(libraryId);
ExploreLabelPO exploreLabel = exploreLabelRepository.getById(apiServiceResponseDTO.getLabelId());
ExploreLabelPO exploreFailLabel = exploreLabelRepository.getById(apiServiceResponseDTO.getFailedLabelId());
if (labelLibraryInfoPO != null) {
apiServiceResponseDTO.setLibraryName(labelLibraryInfoPO.getName());
}
if (exploreLabel != null) {
apiServiceResponseDTO.setLabelName(exploreLabel.getCondName());
}
if (exploreFailLabel != null) {
apiServiceResponseDTO.setFailedLabelName(exploreFailLabel.getCondName());
}
}
}
}
将其通过stream流进行封装,再将其进行组装后即可遍历获得,在领域模型下本人探究心得
java //1. libraryIds---组装获取libraryName信息 List<String> libraryIds = apiServiceResponseDTOIPage.getRecords().stream().map(ApiServiceResponseDTO::getLibraryId).collect(Collectors.toList()); List<LabelLibraryInfoPO> poc1 = labelLibrayInfoMapper.getLibraryIds(libraryIds); Map<String, String> libraryName = poc1.stream().collect(Collectors.toMap(LabelLibraryInfoPO::getPkId, LabelLibraryInfoPO::getName)); //2. labelIds---组装获取condName信息 List<String> labelIds = apiServiceResponseDTOIPage.getRecords().stream().map(ApiServiceResponseDTO::getLabelId).collect(Collectors.toList()); List<ExploreLabelPO> poc2 = exploreLabelRepository.getLabelIds(labelIds); Map<String,String> condName = poc2.stream().collect(Collectors.toMap(ExploreLabelPO::getPkId,ExploreLabelPO::getCondName)); //3. failedLabelIds---组装获取condName信息 List<String> failedLabelIds = apiServiceResponseDTOIPage.getRecords().stream().map(ApiServiceResponseDTO::getFailedLabelId).collect(Collectors.toList()); List<ExploreLabelPO> poc3 = exploreLabelRepository.getFailedLabelIds(failedLabelIds); Map<String,String> condName2 = poc3.stream().collect(Collectors.toMap(ExploreLabelPO::getPkId,ExploreLabelPO::getCondName)); //4.遍历 apiServiceResponseDTOIPage.getRecords().forEach(item -> { if (CollUtil.isNotEmpty(libraryName)){ item.setLibraryName(libraryName.get(item.getLibraryId())); } if (CollectionUtils.isNotEmpty(labelIds)){ item.setLabelName(condName.get(item.getLabelId())); } if (CollectionUtils.isNotEmpty(failedLabelIds)){ item.setFailedLabelName(condName2.get(item.getFailedLabelId())); } });
)
idea自带功能
1、写一个没有返回值的方法
2、参数是ApiServiceResponseDTO 这个实体
3、把你那for循环里面的代码提取出来不就行了
4、为了好看可以用Optional来替换非空if判断