代码优化 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);
时间: 2024-03-01 22:53:44 浏览: 78
可以考虑对代码进行以下优化:
1. 首先可以对 `excelToShopIdList1()` 方法进行优化,使其返回一个 `List<EquDeviceTslProperty>` 类型的结果,避免后面的类型转换。
2. 可以使用 Java8 的 `Optional` 类型来判断 `stringStringMap` 是否为空,避免使用 `CollectionUtils.isEmpty()` 方法。
3. 可以使用 Java8 的 `stream()` 方法和 `map()` 方法来将 `stringList` 转换成 `List<EquDeviceTslProperty>` 类型,避免使用 `forEach()` 方法。
4. 可以将 `excelResult` 和 `saveList` 合并成一个列表,避免使用两个列表。
5. 可以使用 Java8 的 `Map.computeIfAbsent()` 方法来避免判断 `equDeviceTslProperties1` 是否为空的操作。
优化后的代码如下所示:
```
List<EquDeviceTslProperty> excelResult = ExcelUtil.excelToShopIdList1(inputStream);
if (stringStringMap.isEmpty()) {
return warn("无数据");
}
List<EquDeviceTslProperty> saveList = new ArrayList<>();
Map<String, List<EquDeviceTslProperty>> listMap = equDeviceTslPropertyService.selectEquDeviceTslPropertyList(new EquDeviceTslProperty()
.setDeviceCode(excelResult.get(0).getDeviceCode()))
.stream()
.collect(Collectors.groupingBy(EquDeviceTslProperty::getPropertyId));
excelResult.stream()
.map(ar -> {
List<EquDeviceTslProperty> equDeviceTslProperties1 = listMap.computeIfAbsent(ar.getPropertyId(), k -> new ArrayList<>());
if (equDeviceTslProperties1.isEmpty()) {
saveList.add(ar);
return null;
}
return equDeviceTslProperties1.get(0)
.setValueType(ar.getValueType())
.setSortsIndex(ar.getSortsIndex())
.setPropertyName(ar.getPropertyName());
})
.filter(Objects::nonNull)
.forEach(equDeviceTslPropertyService::updateEquDeviceTslProperty);
if (!saveList.isEmpty()) {
equDeviceTslPropertyService.batchInsert(saveList);
}
```
阅读全文