jdk8 优化以下代码: public List<Map<String, Object>> getQualityDatasource(){ List<Map<String, Object>> resultList = new ArrayList<>(); DataSource dataSourceRaw = iDataSourceClient.queryRawDataSource(); resultList.add(new HashMap<String, Object>() {{ put("id", dataSourceRaw.getId()); put("note", dataSourceRaw.getNote()); put("name", dataSourceRaw.getName()); put("relate_id", dataSourceRaw.getRelateId()); put("type", dataSourceRaw.getType().getDescp().toUpperCase(Locale.ROOT)); }}); DataSource dataSourceModel = iDataSourceClient.queryModelDataSource(); resultList.add(new HashMap<String, Object>() {{ put("id", dataSourceModel.getId()); put("note", dataSourceModel.getNote()); put("name", dataSourceModel.getName()); put("relate_id", dataSourceModel.getRelateId()); put("type", dataSourceModel.getType().getDescp().toUpperCase(Locale.ROOT)); }}); DataSource dataSourceTheme = iDataSourceClient.queryThemeDataSource(); resultList.add(new HashMap<String, Object>() {{ put("id", dataSourceTheme.getId()); put("note", dataSourceTheme.getNote()); put("name", dataSourceTheme.getName()); put("relate_id", dataSourceTheme.getRelateId()); put("type", dataSourceTheme.getType().getDescp().toUpperCase(Locale.ROOT)); }}); return resultList; }
时间: 2024-02-26 08:56:58 浏览: 68
可以使用 Java 8 的 Stream API 对代码进行优化,代码如下:
```
public List<Map<String, Object>> getQualityDatasource() {
DataSource[] dataSources = {iDataSourceClient.queryRawDataSource(),
iDataSourceClient.queryModelDataSource(),
iDataSourceClient.queryThemeDataSource()};
return Arrays.stream(dataSources).map(dataSource -> {
Map<String, Object> map = new HashMap<>();
map.put("id", dataSource.getId());
map.put("note", dataSource.getNote());
map.put("name", dataSource.getName());
map.put("relate_id", dataSource.getRelateId());
map.put("type", dataSource.getType().getDescp().toUpperCase(Locale.ROOT));
return map;
}).collect(Collectors.toList());
}
```
这里使用了数组来存储数据源,然后使用 Stream API 对每个数据源进行处理,将其转换为一个 Map,并将所有 Map 收集到一个 List 中返回。
阅读全文