for (Map.Entry<String, List<SysEquipmentAxisResp>> stringListEntry : collect.entrySet()) { JSONObject device = new JSONObject(); int sum1 =0; device.put("storeIds", stringListEntry.getKey()); List<SysEquipmentAxisResp> sysEquipmentInfos1 = collect.get(stringListEntry.getKey()); List<NewSysEquipmentAxisResp> newSysEquipmentInfos = new ArrayList<>(); if (!ObjectUtils.isEmpty(example.getStoreId())) { for (SysEquipmentAxisResp sysEquipmentAxisResp : sysEquipmentInfos1) { NewSysEquipmentAxisResp newSysEquipmentAxisResp = new NewSysEquipmentAxisResp(); BeanUtils.copyProperties(sysEquipmentAxisResp,newSysEquipmentAxisResp); SysVideoInfo sysVideoInfo = videoInfoMapper.selectByStreamInfoId((newSysEquipmentAxisResp.getStreamInfoId()); newSysEquipmentAxisResp.setMonitorRoll(sysVideoInfo.getMonitorRoll()); newSysEquipmentAxisResp.setMonitorYaw(sysVideoInfo.getMonitorYaw()); newSysEquipmentAxisResp.setMonitorPitch(sysVideoInfo.getMonitorPitch()); newSysEquipmentAxisResp.setHeartX(sysVideoInfo.getHeartX()); newSysEquipmentAxisResp.setHeartY(sysVideoInfo.getHeartY()); newSysEquipmentAxisResp.setHeartZ(sysVideoInfo.getHeartZ()); newSysEquipmentInfos.add(newSysEquipmentAxisResp); } device.put("list", newSysEquipmentInfos); } sum1 = sysEquipmentInfos1.stream().mapToInt(SysEquipmentAxisResp::getEquipmentState).sum(); device.put("equipmentState",sum1); floorArr.add(device); }优化下代码
时间: 2024-03-21 08:40:05 浏览: 57
List<Long>转一维数组 Long[](csdn)————程序.pdf
5星 · 资源好评率100%
可以考虑使用Lambda表达式和Stream API来简化代码,同时避免循环中的冗余判断和变量的多次赋值。具体优化方法如下:
```
List<JSONObject> floorArr = collect.entrySet().stream().map(stringListEntry -> {
JSONObject device = new JSONObject();
device.put("storeIds", stringListEntry.getKey());
List<NewSysEquipmentAxisResp> newSysEquipmentInfos = stringListEntry.getValue().stream().map(sysEquipmentAxisResp -> {
NewSysEquipmentAxisResp newSysEquipmentAxisResp = new NewSysEquipmentAxisResp();
BeanUtils.copyProperties(sysEquipmentAxisResp, newSysEquipmentAxisResp);
SysVideoInfo sysVideoInfo = videoInfoMapper.selectByStreamInfoId(newSysEquipmentAxisResp.getStreamInfoId());
newSysEquipmentAxisResp.setMonitorRoll(sysVideoInfo.getMonitorRoll());
newSysEquipmentAxisResp.setMonitorYaw(sysVideoInfo.getMonitorYaw());
newSysEquipmentAxisResp.setMonitorPitch(sysVideoInfo.getMonitorPitch());
newSysEquipmentAxisResp.setHeartX(sysVideoInfo.getHeartX());
newSysEquipmentAxisResp.setHeartY(sysVideoInfo.getHeartY());
newSysEquipmentAxisResp.setHeartZ(sysVideoInfo.getHeartZ());
return newSysEquipmentAxisResp;
}).collect(Collectors.toList());
if (!ObjectUtils.isEmpty(example.getStoreId())) {
device.put("list", newSysEquipmentInfos);
}
int sum1 = stringListEntry.getValue().stream().mapToInt(SysEquipmentAxisResp::getEquipmentState).sum();
device.put("equipmentState", sum1);
return device;
}).collect(Collectors.toList());
```
使用Stream API可以将遍历、转换和收集操作合并到一起,使代码更加简洁易懂。同时,避免了冗余判断和变量的多次赋值,提高了代码的效率。
阅读全文