优化 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); } } }
时间: 2023-12-31 10:05:19 浏览: 64
这段代码的主要功能是将一个数据结构进行转换,并将转换后的结果装饰到数据模型中。下面是一些优化建议:
1. 使用stream API来简化代码,提高可读性和可维护性。
2. 使用Optional类来避免对null进行判断。
3. 使用更具有描述性的变量名来提高可读性。
4. 将List转换为Set来提高查找效率。
下面是优化后的代码:
```
private void addReferencedKpi(List<AnalysisTableDto> tableDtoList, List<String> codeList, List<Map<String, List<String>>> referencedList) {
if (CollectionUtils.isEmpty(tableDtoList) || CollectionUtils.isEmpty(codeList) || CollectionUtils.isEmpty(referencedList)) {
return;
}
Map<String, Map<String, Set<String>>> tableColumnWithCodeMap = new HashMap<>();
IntStream.range(0, referencedList.size())
.filter(i -> MapUtils.isNotEmpty(referencedList.get(i)))
.forEach(i -> {
String code = codeList.get(i);
referencedList.get(i).forEach((table, columns) -> {
Map<String, Set<String>> columnWithCodeMap = tableColumnWithCodeMap.computeIfAbsent(table, k -> new HashMap<>());
columns.forEach(column -> columnWithCodeMap.computeIfAbsent(column, k -> new HashSet<>()).add(code));
});
});
tableDtoList.forEach(tableDto -> {
String tableName = tableDto.getTableName();
tableDto.getColumns().stream()
.filter(column -> tableColumnWithCodeMap.containsKey(tableName) && tableColumnWithCodeMap.get(tableName).containsKey(column.getTitle()))
.forEach(column -> column.setReferencedKpis(tableColumnWithCodeMap.get(tableName).get(column.getTitle())));
});
}
```
阅读全文