代码优化 List<DeviceDataShow> DeviceDataShows = new ArrayList<>(); if (StringUtils.isNotEmpty(deviceCode)) { try { EquDeviceTslProperty tslProperty = new EquDeviceTslProperty(); tslProperty.setDeviceCode(deviceCode); List<EquDeviceTslProperty> equDeviceTslProperties = equDeviceTslPropertyService.selectEquDeviceTslPropertyList(tslProperty); equDeviceTslProperties = equDeviceTslProperties.subList(0, 8); equDeviceTslProperties.forEach(ar->{ RealTimeData deviceRealTimeData = this.getDeviceRealTimeData(deviceCode, ar.getPropertyId()); DeviceDataShow deviceDataShow = new DeviceDataShow(); BeanUtils.copyBeanProp(deviceDataShow,deviceRealTimeData); BeanUtils.copyBeanProp(deviceDataShow,ar); DeviceDataShows.add(deviceDataShow); }); } catch (Exception e) { log.error("获取设备数据失败!"); } }
时间: 2024-02-14 11:05:34 浏览: 121
这段代码可以进行以下优化:
1. 在使用前可以检查一下 `deviceCode` 是否为空,避免不必要的查询和计算。
2. 如果 `equDeviceTslProperties` 的长度小于8,可以避免调用 `subList()` 方法。
3. 可以使用 lambda 表达式来代替 forEach 循环,使代码更加简洁。
4. 可以使用 try-with-resources 语句来自动关闭资源,避免资源泄漏。
下面是优化后的代码:
```java
if (StringUtils.isNotEmpty(deviceCode)) {
try {
EquDeviceTslProperty tslProperty = new EquDeviceTslProperty();
tslProperty.setDeviceCode(deviceCode);
List<EquDeviceTslProperty> equDeviceTslProperties = equDeviceTslPropertyService.selectEquDeviceTslPropertyList(tslProperty);
if (equDeviceTslProperties.size() > 8) {
equDeviceTslProperties = equDeviceTslProperties.subList(0, 8);
}
DeviceDataShows = equDeviceTslProperties.stream()
.map(ar -> {
RealTimeData deviceRealTimeData = this.getDeviceRealTimeData(deviceCode, ar.getPropertyId());
DeviceDataShow deviceDataShow = new DeviceDataShow();
BeanUtils.copyBeanProp(deviceDataShow, deviceRealTimeData);
BeanUtils.copyBeanProp(deviceDataShow, ar);
return deviceDataShow;
})
.collect(Collectors.toList());
} catch (Exception e) {
log.error("获取设备数据失败!", e);
}
}
```
阅读全文