List<ResourceStandingBookVo> getResourceStandingBookVos(List<OrganizationLevelVo> vos, List<ResourceStandingBookVo> bookVos) { List<ResourceStandingBookVo> standingBookVos = new ArrayList<>(); for (int i = 0; i <vos.size() ; i++) { ResourceStandingBookVo resourceStandingBookVo = new ResourceStandingBookVo(); for (int j = 0; j < bookVos.size(); j++) { if (i==j) { if (vos.get(i).getOrgIds().contains(bookVos.get(j).getUnitId())) { ResourceStandingBookVo standingBookVo = MapperUtils.mapping(bookVos.get(j), ResourceStandingBookVo.class); standingBookVo.setUnitId(vos.get(i).getId()); standingBookVo.setUnit(vos.get(i).getOrgOtherName()); standingBookVos.add(standingBookVo); break; } else { resourceStandingBookVo.setUnitId(vos.get(i).getId()); resourceStandingBookVo.setUnit(vos.get(i).getOrgOtherName()); standingBookVos.add(resourceStandingBookVo); break; } } } }把这段代码优化一下
时间: 2023-12-12 10:02:53 浏览: 74
可以优化的地方有:
1. 双重循环可以改为单层循环,使用 Stream API 来实现
2. 避免在循环内创建对象,可以在循环外部创建对象,避免不必要的开销
3. 在最外层的循环中,可以使用变量来存储 vos.get(i),避免多次调用
优化后的代码如下:
```
List<ResourceStandingBookVo> getResourceStandingBookVos(List<OrganizationLevelVo> vos, List<ResourceStandingBookVo> bookVos) {
List<ResourceStandingBookVo> standingBookVos = new ArrayList<>();
for (OrganizationLevelVo vo : vos) {
ResourceStandingBookVo resourceStandingBookVo = new ResourceStandingBookVo();
bookVos.stream()
.filter(bookVo -> vos.indexOf(vo) == bookVos.indexOf(bookVo))
.findFirst()
.ifPresent(bookVo -> {
if (vo.getOrgIds().contains(bookVo.getUnitId())) {
ResourceStandingBookVo standingBookVo = MapperUtils.mapping(bookVo, ResourceStandingBookVo.class);
standingBookVo.setUnitId(vo.getId());
standingBookVo.setUnit(vo.getOrgOtherName());
standingBookVos.add(standingBookVo);
} else {
resourceStandingBookVo.setUnitId(vo.getId());
resourceStandingBookVo.setUnit(vo.getOrgOtherName());
standingBookVos.add(resourceStandingBookVo);
}
});
}
return standingBookVos;
}
```
相关推荐
![crx](https://img-home.csdnimg.cn/images/20210720083646.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)