优化下段代码 Map<String, List<StkTransferOrderDtl>> collect = stkTransferOrderDtls.stream().collect(Collectors.groupingBy(StkTransferOrderDtl::getProjId)); collect.forEach((projId,stkTransferOrderDtlList)->{ List<String> bigClassCodes = stkTransferOrderDtlList.stream().map(p->{ return p.getMatCode().substring(0,2); }).distinct().collect(Collectors.toList()); for (String bigClassCode : bigClassCodes) {}
时间: 2023-12-10 16:40:46 浏览: 105
可以尝试将两个Stream合并成一个来提高效率,代码如下:
```
Map<String, List<String>> collect = stkTransferOrderDtls.stream()
.collect(Collectors.groupingBy(StkTransferOrderDtl::getProjId,
Collectors.mapping(p -> p.getMatCode().substring(0, 2),
Collectors.collectingAndThen(Collectors.toSet(), ArrayList::new))));
collect.forEach((projId, bigClassCodes) -> {
for (String bigClassCode : bigClassCodes) {
// do something
}
});
```
这里使用了`Collectors.mapping()`和`Collectors.collectingAndThen()`方法来进行分组和去重操作,同时将结果转换为ArrayList,以便后续的遍历操作。
相关问题
优化这段代码 Map<String, List<MonitorRuleMetricDO>> collect = conditionMetrics.stream().collect(Collectors.groupingBy(MonitorRuleMetricDO::getMetricName));
Map<String, List<MonitorRuleMetricDO>> collect = conditionMetrics.stream()
.collect(Collectors.groupingBy(
MonitorRuleMetricDO::getMetricName));
将Map<String, List<DictResponseVO>> collect = dictTree.stream().collect(Collectors.groupingBy(DictResponseVO::getCode));的结果修改为Map<String, Map<String, List<DictResponseVO>>>
可以使用Collectors.groupingBy嵌套来完成这个转换,代码如下:
```
Map<String, Map<String, List<DictResponseVO>>> collect = dictTree.stream()
.collect(Collectors.groupingBy(DictResponseVO::getCode, Collectors.groupingBy(DictResponseVO::getType)));
```
这样就可以按照code和type两个属性进行分组,得到一个嵌套的Map。其中外层Map的key是code,value是内层Map;内层Map的key是type,value是对应的DictResponseVO列表。
阅读全文