我正在寻找一些帮助来清理下面的代码并减少行数。如果get返回null,是否可以不设置任何内容?
if (map.get("cpn_rate") != null) {
collateral.setCoupon(new BigDecimal(map.get("cpn_rate")));
}
if (map.get("Price") != null) {
collateral.setPrice(new BigDecimal(map.get("Price")));
}
if (map.get("Par") != null) {
collateral.setPar(new BigDecimal(map.get("Par")));
}
if (map.get("mkt_val") != null) {
collateral.setMarketValue(new BigDecimal(map.get("mkt_val")));
}
if (map.get("Accrued Intr") != null) {
collateral.setAccurInterest(new BigDecimal(map.get("Accrued Intr")));
}
if (map.get("Total Market Value") != null) {
collateral.setTotMktValue(new BigDecimal(map.get("Total Market Value")));
}
这里我只是将这些键存储在字符串数组中,然后进行遍历并检查它们是否为null。如果它们不存在,那么我们添加它们。
String[] keys = new String[]{"cpn_rate","Price","Par","mkt_val","Accrued Intr","Total Market Value"};
for(String key : keys){
if(map.get(key) != null){
collateral.setPar(new BigDecimal(map.get(key)));
}
}
尝试一下:
for (String key : map.keySet()){
if (map.get(key) != null) {
collateral.setPrice(new BigDecimal(map.get("Price")));
}
}
假设映射中的所有键都是字符串。