代码优化 List<String> stringList = ExcelUtil.excelToShopIdList1(inputStream); if (CollectionUtils.isEmpty(stringStringMap)) { return warn("无数据"); } List<EquDeviceTslProperty> excelResult = new ArrayList<>(); stringList.forEach(ar->{ EquDeviceTslProperty equDeviceTslProperty = JSON.parseObject(ar, EquDeviceTslProperty.class); excelResult.add(equDeviceTslProperty); }); EquDeviceTslProperty deviceTslProperty = new EquDeviceTslProperty(); deviceTslProperty.setDeviceCode(excelResult.get(0).getDeviceCode()); List<EquDeviceTslProperty> equDeviceTslProperties = equDeviceTslPropertyService.selectEquDeviceTslPropertyList(deviceTslProperty); List<EquDeviceTslProperty> saveList = new ArrayList<>(); Map<String, List<EquDeviceTslProperty>> listMap = equDeviceTslProperties.stream().collect(Collectors.groupingBy(EquDeviceTslProperty::getPropertyId)); excelResult.forEach(ar->{ List<EquDeviceTslProperty> equDeviceTslProperties1 = listMap.get(ar.getPropertyId()); if (CollectionUtils.isEmpty(equDeviceTslProperties1)) { saveList.add(ar); return; } equDeviceTslProperties1.get(0).setValueType(ar.getValueType()) .setSortsIndex(ar.getSortsIndex()) .setPropertyName(ar.getPropertyName()); equDeviceTslPropertyService.updateEquDeviceTslProperty(equDeviceTslProperties1.get(0)); }); equDeviceTslPropertyService.batchInsert(saveList);
时间: 2023-08-07 19:03:22 浏览: 99
可以考虑使用Java8的stream API来简化代码:
```
List<String> stringList = ExcelUtil.excelToShopIdList1(inputStream);
if (CollectionUtils.isEmpty(stringList)) {
return warn("无数据");
}
List<EquDeviceTslProperty> excelResult = stringList.stream()
.map(ar -> JSON.parseObject(ar, EquDeviceTslProperty.class))
.collect(Collectors.toList());
String deviceCode = excelResult.get(0).getDeviceCode();
List<EquDeviceTslProperty> equDeviceTslProperties = equDeviceTslPropertyService.selectEquDeviceTslPropertyList(new EquDeviceTslProperty().setDeviceCode(deviceCode));
Map<String, List<EquDeviceTslProperty>> listMap = equDeviceTslProperties.stream().collect(Collectors.groupingBy(EquDeviceTslProperty::getPropertyId));
List<EquDeviceTslProperty> saveList = excelResult.stream()
.filter(ar -> CollectionUtils.isEmpty(listMap.get(ar.getPropertyId())))
.collect(Collectors.toList());
listMap.forEach((propertyId, properties) -> {
excelResult.stream()
.filter(ar -> propertyId.equals(ar.getPropertyId()))
.findFirst()
.ifPresent(ar -> {
EquDeviceTslProperty property = properties.get(0);
property.setValueType(ar.getValueType())
.setSortsIndex(ar.getSortsIndex())
.setPropertyName(ar.getPropertyName());
equDeviceTslPropertyService.updateEquDeviceTslProperty(property);
});
});
equDeviceTslPropertyService.batchInsert(saveList);
```
这样可以更清晰地表达出代码的逻辑,并且减少了一些不必要的中间变量的使用。
阅读全文