优化以下代码 Map<String, Integer> resultMap = new HashMap<>(); List<StubDiffTimeDiscountBO> list = new ArrayList<>(); for (StubDiffTimeDiscountBO stubDiscountBO : boList) { String tmp = stubDiscountBO.getStupGroupId(); int count = resultMap.get(tmp) != null ? resultMap.get(tmp) : 0; count = count + 1; resultMap.put(tmp, count); } resultMap.keySet().stream().filter(getKey -> resultMap.get(getKey) != 1).forEach(getKey -> { StubDiffTimeDiscountBO bo = new StubDiffTimeDiscountBO(); bo.setStupGroupId(getKey); list.add(bo); }); List<String> repeatIdList = list.stream().map(StubDiffTimeDiscountBO::getStupGroupId).collect(Collectors.toList());
时间: 2024-03-05 18:53:18 浏览: 230
String 优化
优化后的代码如下:
```
Map<String, Integer> resultMap = new HashMap<>();
List<String> repeatIdList = new ArrayList<>();
for (StubDiffTimeDiscountBO stubDiscountBO : boList) {
String tmp = stubDiscountBO.getStupGroupId();
int count = resultMap.getOrDefault(tmp, 0);
count++;
resultMap.put(tmp, count);
if (count == 2) {
repeatIdList.add(tmp);
}
}
List<StubDiffTimeDiscountBO> list = repeatIdList.stream().map(id -> {
StubDiffTimeDiscountBO bo = new StubDiffTimeDiscountBO();
bo.setStupGroupId(id);
return bo;
}).collect(Collectors.toList());
```
优化的细节如下:
1. 用`Map.getOrDefault`方法替代`Map.get`方法判断null的情况;
2. 用if语句判断重复次数,避免多次遍历结果集;
3. 用`stream`流替代原来的`keySet`方法,避免多次遍历结果集;
4. 直接用`map`方法映射`StubDiffTimeDiscountBO`对象,避免手动添加到`list`中。
阅读全文