public List<HospitalDeviceEntity> queryDeviceByBuildingAndFloor(HospitalServiceRoomQueryModel queryModel) { //获取全部设备信息 HospitalReq hospitalReq = new HospitalReq(); List<HospitalDeviceEntity> hospitalDeviceEntities = queryDevice(hospitalReq); //按条件筛选返回前端 List<HospitalDeviceEntity> result = new ArrayList<>(); for (HospitalDeviceEntity entity : hospitalDeviceEntities) { if (queryModel.getLy() != null && queryModel.getLc() != null){ if (queryModel.getLc().equals(entity.getFloor()) && queryModel.getLy().equals(entity.getBuilding())){ result.add(entity); } } } return result; }优化代码
时间: 2024-02-14 18:12:59 浏览: 21
可以通过以下方式来优化代码:
1. 避免重复查询设备信息,可以将查询结果缓存起来,避免每次都查询全部设备信息。
2. 使用 Java 8 的 Stream API,将循环遍历转换为流式操作,提高代码的简洁性和可读性。
3. 使用 Java 8 的 Optional 类来避免空指针异常,提高代码的健壮性。
下面是优化后的代码:
```
public List<HospitalDeviceEntity> queryDeviceByBuildingAndFloor(HospitalServiceRoomQueryModel queryModel) {
//获取全部设备信息
HospitalReq hospitalReq = new HospitalReq();
List<HospitalDeviceEntity> hospitalDeviceEntities = queryDevice(hospitalReq);
//按条件筛选返回前端
return hospitalDeviceEntities.stream()
.filter(entity -> Optional.ofNullable(queryModel.getLy()).orElse("").equals(entity.getBuilding()))
.filter(entity -> Optional.ofNullable(queryModel.getLc()).orElse("").equals(entity.getFloor()))
.collect(Collectors.toList());
}
```
优化后的代码使用了 Java 8 的 Stream API,将循环遍历转换为流式操作,同时使用 Optional 类来避免空指针异常。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)