List<BusinessAreaNameAndTableName> businessAreaNameAndTableNames = dataInfoMapper.selectBusinessDomainName(tabNames); Map<String,Set<String>> map =new HashMap<>(); for (int i = 0; i < businessAreaNameAndTableNames.size(); i++) { Set<String> value = new HashSet<>(); map.put(businessAreaNameAndTableNames.get(i).getTabName(),value); value.clear(); for (int j = 0; j < businessAreaNameAndTableNames.size(); j++) { if (businessAreaNameAndTableNames.get(i).getTabName().equals(businessAreaNameAndTableNames.get(j).getTabName())){ String businessAreaName = businessAreaNameAndTableNames.get(j).getBusinessAreaName(); value.add(businessAreaName); } } }通过java stream流优化
时间: 2024-02-06 21:11:13 浏览: 100
java中List、Array、Map、Set等集合相互转换
可以使用Java 8的Stream API对这段代码进行优化,可以尝试以下代码:
```
Map<String, Set<String>> map = businessAreaNameAndTableNames.stream()
.collect(Collectors.groupingBy(
BusinessAreaNameAndTableName::getTabName,
Collectors.mapping(BusinessAreaNameAndTableName::getBusinessAreaName, Collectors.toSet())
));
```
这段代码通过Stream的`groupingBy`方法将`BusinessAreaNameAndTableName`对象按照`tabName`属性进行分组,并将`businessAreaName`属性映射为一个Set集合,最终得到一个`Map<String, Set<String>>`类型的结果。这样可以避免使用循环和中间的`HashMap`对象,使代码更加简洁和易读。
阅读全文