优化 private void addReferencedKpi(List<AnalysisTableDto> list, List<String> codeList, List<Map<String, List<String>>> referencedList) { if (CollectionUtils.isEmpty(list) || CollectionUtils.isEmpty(codeList) || CollectionUtils.isEmpty(referencedList)) { return; } // 转换结构 key1-table key2-column value-codeList Map<String, Map<String, List<String>>> tableColumnWithCodeListMap = Maps.newHashMap(); int size = referencedList.size(); for (int i = 0; i < size; i++) { String code = codeList.get(i); Map<String, List<String>> referencedPerMap = referencedList.get(i); if (MapUtils.isEmpty(referencedPerMap)) { continue; } referencedPerMap.forEach((table, columns) -> { tableColumnWithCodeListMap.putIfAbsent(table, Maps.newHashMap()); for (String column : columns) { tableColumnWithCodeListMap.get(table).putIfAbsent(column, Lists.newArrayList()); tableColumnWithCodeListMap.get(table).get(column).add(code); } }); } // 装饰引用kpi for (AnalysisTableDto simulationTableDto : list) { String simTableName = simulationTableDto.getTableName(); for (SimulationColumnDto column : simulationTableDto.getColumns()) { String simTitle = column.getTitle(); if (!tableColumnWithCodeListMap.containsKey(simTableName) || !tableColumnWithCodeListMap.get(simTableName).containsKey(simTitle)) { continue; } List<String> referencedCodeList = tableColumnWithCodeListMap.get(simTableName).get(simTitle); column.setReferencedKpis(referencedCodeList); } } }
时间: 2024-02-01 17:02:00 浏览: 113
可以考虑以下几点进行优化:
1. 将代码分解为更小的方法,提高可读性和可维护性。
2. 使用Java 8+的Stream API代替循环和条件语句,使代码更简洁。
3. 可以使用Google Guava库提供的Multimap类来代替手动创建的tableColumnWithCodeListMap,从而简化代码。
4. 使用针对null的断言操作符(Java 11+)来简化空值检查。
下面是参考示例代码:
```java
private void addReferencedKpi(List<AnalysisTableDto> list, List<String> codeList, List<Map<String, List<String>>> referencedList) {
if (list == null || codeList == null || referencedList == null) {
return;
}
// 转换结构 key1-table key2-column value-codeList
Multimap<String, String> tableColumnWithCodeListMap = Multimaps.newListMultimap(
Maps.newHashMap(), () -> Lists.newArrayList());
IntStream.range(0, codeList.size())
.forEach(i -> {
String code = codeList.get(i);
Map<String, List<String>> referencedPerMap = referencedList.get(i);
if (referencedPerMap != null) {
referencedPerMap.forEach((table, columns) ->
columns.forEach(column ->
tableColumnWithCodeListMap.put(table + "_" + column, code)));
}
});
// 装饰引用kpi
list.forEach(tableDto ->
tableDto.getColumns().forEach(column -> {
String simTableName = tableDto.getTableName();
String simTitle = column.getTitle();
List<String> referencedCodeList = tableColumnWithCodeListMap.get(simTableName + "_" + simTitle);
column.setReferencedKpis(referencedCodeList);
}));
}
```
阅读全文