优化这段代码 List<Map<String, String>> topModel = new ArrayList<>(); List<Map<String, String>> imageTextModel = new ArrayList<>(); List<Map<String, String>> listModel = new ArrayList<>(); List<Map<String, String>> videoModel = new ArrayList<>(); List<Map<String, String>> cardRotationModel = new ArrayList<>(); List<Map<String, String>> otherModel = new ArrayList<>(); // 获取样式模板字典枚举 for (final StyleModel styleModel : StyleModel.class.getEnumConstants()) { final Map<String, String> map = new HashMap<>(); map.put("sign", styleModel.getSign()); map.put("name", styleModel.getName()); switch (styleModel.getType()) { case 1: topModel.add(map); break; case 2: imageTextModel.add(map); break; case 3: listModel.add(map); break; case 4: videoModel.add(map); break; case 5: cardRotationModel.add(map); break; default: otherModel.add(map); } } BaseEnumUtil.getStyleModel().add(new HashMap<>() {{ put("name", "顶部模板"); put("list", topModel); }}); BaseEnumUtil.getStyleModel().add(new HashMap<>() {{ put("name", "图文模板"); put("list", imageTextModel); }}); BaseEnumUtil.getStyleModel().add(new HashMap<>() {{ put("name", "列表模板"); put("list", listModel); }}); BaseEnumUtil.getStyleModel().add(new HashMap<>() {{ put("name", "视频模板"); put("list", videoModel); }}); BaseEnumUtil.getStyleModel().add(new HashMap<>() {{ put("name", "轮播图模板"); put("list", cardRotationModel); }}); BaseEnumUtil.getStyleModel().add(new HashMap<>() {{ put("name", "其它模板"); put("list", otherModel); }});
时间: 2024-02-27 10:57:47 浏览: 114
可以考虑使用更简洁的代码来优化这段代码:
```
Map<Integer, List<Map<String, String>>> map = new HashMap<>();
for (final StyleModel styleModel : StyleModel.class.getEnumConstants()) {
final Map<String, String> styleMap = new HashMap<>();
styleMap.put("sign", styleModel.getSign());
styleMap.put("name", styleModel.getName());
List<Map<String, String>> styleList = map.getOrDefault(styleModel.getType(), new ArrayList<>());
styleList.add(styleMap);
map.put(styleModel.getType(), styleList);
}
BaseEnumUtil.getStyleModel().addAll(
Arrays.asList(
new HashMap<>() {{ put("name", "顶部模板"); put("list", map.get(1)); }},
new HashMap<>() {{ put("name", "图文模板"); put("list", map.get(2)); }},
new HashMap<>() {{ put("name", "列表模板"); put("list", map.get(3)); }},
new HashMap<>() {{ put("name", "视频模板"); put("list", map.get(4)); }},
new HashMap<>() {{ put("name", "轮播图模板"); put("list", map.get(5)); }},
new HashMap<>() {{ put("name", "其它模板"); put("list", map.getOrDefault(0, new ArrayList<>())); }}
)
);
```
这样可以避免重复的代码以及多余的变量声明,同时使用了 Java 8 的新特性,代码更加简洁易懂。
阅读全文