优化这段代码 第二次循环groupId的时候 list1里的map 如果key相同 value以,形式隔开
时间: 2024-03-23 20:41:06 浏览: 20
这段代码的性能瓶颈在于每次循环都要遍历list1,时间复杂度为O(n^2),可以通过使用一个Map来代替list1来达到优化的目的。具体做法是在第一次循环时,将list1中的所有数据以时间为key,以Map为value存放在一个新的Map中。第二次循环时,遍历list,通过时间来获取对应的Map,将统计数据中的count值以“,”隔开的形式添加到Map中的value中。代码示例如下:
```
Map<String, Map<String, Object>> map1 = new HashMap<>();
for (String groupId : groupIds) {
Long groupId1 = Long.valueOf(groupId);
List<HkEquipment> hkEquipments = hkEquipmentRepository.findAllByAppIdAndShopIdAndGroupId(appId, shopId, groupId1);
if (hkEquipments.isEmpty()) {
throw new CustomException("该分组没有设备");
}
List<String> cameraUuids = hkEquipments.stream().map(HkEquipment::getCameraUuid).toList();
List<PassengerFlowMonth> yearList = passengerFlowMonthRepository.findAllByAppIdAndShopIdAndCountMonthBetweenAndCameraUuidIn(appId, shopId, Stime, Etime, cameraUuids);
Map<String, Integer> groupData = yearList.stream()
.collect(Collectors.groupingBy(
item -> item.getCountMonth().toString().substring(0, 4),
Collectors.summingInt(item -> Math.toIntExact(item.getInNum()))
));
TreeMap<String, Integer> paramTreeMap = new TreeMap<>(groupData);
paramTreeMap.forEach((K, V) -> {
Map<String, Object> hash = new HashMap<>();
hash.put("time", K);
hash.put("count", V);
map1.put(K, hash);
});
}
for (Map<String, Object> objectMap : list) {
Map<String, Object> map2 = map1.get(objectMap.get("time").toString());
if (map2 != null) {
String count = map2.get("count") + "," + objectMap.get("count");
map2.put("count", count);
}
}
List<Map<String, Object>> list1 = new ArrayList<>(map1.values());
```
在这段优化后的代码中,我们把list1替换成了一个Map,这个Map的key是时间,value是一个Map,包含了时间和count两个属性。在第二次循环中,我们通过时间来获取对应的Map,然后将统计数据中的count以“,”隔开的形式添加到value中。最后,我们将Map中的所有value组成一个新的List返回。这样做可以将时间复杂度降低到O(n),提高代码的运行效率。