public void setProfit(BigDecimal profit, String tradeId, String businessCode,String noteCode) { TradeReportContextData contextData = (TradeReportContextData) reportContextRegister.getContextData(); List<TradeDataMarket> dataMarketList = contextData.getDatemarket(); if(AtsObjectUtils.isEmpty(dataMarketList)){ dataMarketList=new ArrayList<>(); contextData.setDatemarket(dataMarketList); } boolean isNeedNewObject = true; for (TradeDataMarket dataMarket : dataMarketList) { if (dataMarket.getTradeid().equals(tradeId)) { dataMarket.setHedgingcostprofit(profit); isNeedNewObject = false; } } if (isNeedNewObject) { TradeDataMarket dataMarket = new TradeDataMarket(); dataMarket.setHedgingcostprofit(profit) .setTradeid(tradeId) .setDatabatchno(AtsDateUtils.formatDate(AtsDateUtils.newDate(),AtsDateUtils.DATE_FMT)) .setBusinesscode(businessCode) .setNotecode(noteCode); dataMarketList.add(dataMarket); } } 优化这段代码
时间: 2024-02-14 10:11:24 浏览: 165
string转bigdecimal类型.md
以下是对该段代码的优化建议:
1. 建议将常量提取到类的静态常量中,如:private static final String DATE_FMT = "yyyyMMdd"。
2. 建议将方法的参数设置为对象,而不是多个参数,可以提高代码的可读性和可维护性。
3. 建议使用Java8的Stream API来简化代码,如: dataMarketList.stream().filter(dataMarket -> dataMarket.getTradeid().equals(tradeId)).findFirst().ifPresent(dataMarket -> dataMarket.setHedgingcostprofit(profit));
4. 建议通过使用Optional来减少null值检查的代码。
以下是优化后的代码:
```
public void setProfit(TradeDataMarket dataMarket, BigDecimal profit) {
TradeReportContextData contextData = reportContextRegister.getContextData();
List<TradeDataMarket> dataMarketList = contextData.getDatemarket();
if (CollectionUtils.isEmpty(dataMarketList)) {
dataMarketList = new ArrayList<>();
contextData.setDatemarket(dataMarketList);
}
dataMarketList.stream().filter(dm -> dm.getTradeid().equals(dataMarket.getTradeid())).findFirst()
.ifPresentOrElse(dm -> dm.setHedgingcostprofit(profit), () -> {
dataMarketList.add(new TradeDataMarket().setHedgingcostprofit(profit)
.setTradeid(dataMarket.getTradeid())
.setDatabatchno(AtsDateUtils.formatDate(AtsDateUtils.newDate(), DATE_FMT))
.setBusinesscode(dataMarket.getBusinesscode())
.setNotecode(dataMarket.getNotecode()));
});
}
```
阅读全文