优化这段代码: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 17:48:42 浏览: 98
可以使用Java 8的Stream API来重写这段代码,代码如下:
```
private List<DynamicSource> getDynamicSourceList(List<DasymesQltyMpCertfInfoItemMod> itemModList) {
List<Map<String, String>> mapList = Optional.ofNullable(itemModList)
.orElseGet(Collections::emptyList)
.stream()
.map(item -> {
Map<String, String> map = new HashMap<>();
map.put("no", String.valueOf(itemModList.indexOf(item) + 1));
map.put("name", item.getItemName());
map.put("portion", item.getPortion());
return map;
})
.collect(Collectors.toList());
if (mapList.isEmpty()) {
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);
}
```
这里使用了Optional来避免对空List进行null检查,使用Stream API来处理List数据并返回一个新的List。同时将代码中的循环和判断合并到了一起,使代码更加简洁易读。
阅读全文