优化这段代码:private List<DynamicSource> getDynamicSourceList(List<DasymesQltyMpCertfInfoItemMod> itemModList) { List<Map<String, String>> mapList = new ArrayList<>(); if (itemModList == null || itemModList.size() == 0) { Map<String, String> map = new HashMap<>(); map.put("no", null); map.put("name", null); map.put("portion", null); mapList.add(map); return DynamicSource.createList("detail", mapList); } for (int i = 1; i <= itemModList.size(); i++) { DasymesQltyMpCertfInfoItemMod item = itemModList.get(i - 1); Map<String, String> map = new HashMap<>(); map.put("no", i + ""); map.put("name", item.getItemName()); map.put("portion", item.getPortion()); mapList.add(map); } return DynamicSource.createList("detail", mapList); }
时间: 2024-03-02 22:52:32 浏览: 16
可以优化的地方如下:
1. 在if语句中,可以直接创建map并添加到mapList中,避免了在后面的循环中再创建map。
2. 在循环中,可以使用foreach循环代替for循环,避免了使用i变量。
3. 在创建DynamicSource时,可以直接使用mapList,不需要再创建一个中间变量。
优化后的代码如下:
```
private List<DynamicSource> getDynamicSourceList(List<DasymesQltyMpCertfInfoItemMod> itemModList) {
List<Map<String, String>> mapList = new ArrayList<>();
if (itemModList == null || itemModList.isEmpty()) {
mapList.add(Map.of(
"no", null,
"name", null,
"portion", null
));
} else {
for (DasymesQltyMpCertfInfoItemMod item : itemModList) {
Map<String, String> map = new HashMap<>();
map.put("no", String.valueOf(mapList.size() + 1));
map.put("name", item.getItemName());
map.put("portion", item.getPortion());
mapList.add(map);
}
}
return DynamicSource.createList("detail", mapList);
}
```
这样代码更加简洁易读,也更加高效。