优化代码
时间: 2023-08-11 14:16:55 浏览: 49
这段代码的主要作用是根据医院的发药单ID获取药品的发药明细列表,并根据药品名称进行汇总,然后判断每个药品的库存数量是否足够,最终返回发药单明细列表。可以考虑以下优化:
1. 对于库存查询,可以使用批量查询来优化性能,避免多次单独查询库存信息。
2. 对于药品名称汇总的部分,可以尝试使用Java 8的新特性进行简化,例如使用`Collectors.groupingBy()`方法进行分组,再使用`Collectors.toMap()`方法进行汇总。
3. 对于药品库存判断的部分,可以使用三元表达式来简化判断逻辑。
优化后的代码如下所示:
```
List<HospitalizationReceivingMedicineVO> details = hospitalizationReceivingMedicineMapper.getDispensing(id);
// 根据药品名称汇总
Map<Long, HospitalizationReceivingMedicineVO> collect = details.stream()
.collect(Collectors.groupingBy(HospitalizationReceivingMedicineVO::getMedicineId,
Collectors.reducing(null, (x, y) -> {
if (x == null) {
return new HospitalizationReceivingMedicineVO(y);
} else {
x.setAmount(x.getAmount() + y.getAmount());
x.setTotalPrice(x.getUnitPrice().multiply(BigDecimal.valueOf(x.getAmount())));
return x;
}
})));
List<HospitalizationReceivingMedicineVO> hospitalizationReceivingMedicineList = new ArrayList<>(collect.values());
List<Long> idList = hospitalizationReceivingMedicineList.stream().map(HospitalizationReceivingMedicineVO::getMedicineId)
.collect(Collectors.toList());
if (idList.isEmpty()) {
throw new RuntimeException("没有查询到库存信息,请检查");
}
Map<Long, StockBO> data = stockClient.listByGoodsIds(idList).getData();
// 将发药单集合分为有库存的和没有库存的
hospitalizationReceivingMedicineList.forEach(x -> x.setIsStock(data.get(x.getMedicineId()).getPackCount() >= x.getAmount() ? 1 : 0));
return hospitalizationReceivingMedicineList;
```
相关推荐
![](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)