private List<String> V51DKJsonToBinList(List<LightGroupReq> lightGroupReqs){ LinkedHashMap<Long, List<Frames>> groupingFrames = jsonToBinPub(lightGroupReqs,VehicleConstants.VEHICLE_009); ArrayList<String> list = new ArrayList<>(); Map<Integer, Frames> portMap = new HashMap<>(); List<Frames> frameList = new ArrayList<>(); for (int i = 1; i <= 41; i++) { frameList.add(new Frames(255, 255, 2550, 2550, 255, 255, 0, i, 0, 2)); } groupingFrames.put((long) groupingFrames.size(), frameList); long timeStamp = 0; for (Map.Entry<Long, List<Frames>> entry : groupingFrames.entrySet()) { List<Frames> framesList = entry.getValue(); int[] temp = new int[42]; //全部初始化为-1 Arrays.fill(temp, -1); for (int i = 0; i < framesList.size(); i++) { temp[framesList.get(i).getGroupIndex()] = 1; } for (int i = 1; i < temp.length; i++) { if (temp[i] == -1) { portMap.put(i, new Frames(255, 255, 2550, 2550, 255, 255, 0, i, 0, 2)); } } framesList.addAll(portMap.values()); framesList = framesList.stream().sorted(Comparator.comparing(Frames::getGroupIndex)).collect(Collectors.toList()); portMap.clear(); if(timeStamp>7){ timeStamp = 0; } for (int j = 0; j < framesList.size(); j++) { list.add(BinaryFileUtils.V51DKFramesToHex(framesList.get(j),framesList.get(j).getGroupIndex(),timeStamp)); } timeStamp++; } return list; }优化这段代码
时间: 2024-01-20 10:02:06 浏览: 126
以下是对代码的一些优化建议:
1. 变量名命名规范化,按照Java语言规范,变量名应该采用驼峰命名法,首字母小写。
2. 在循环中,应该使用StringBuilder来拼接字符串,而不是使用List,因为List的add操作会频繁地进行数组扩容,影响性能。
3. 在循环中,应该将不变的变量提到循环外面,避免重复初始化。
4. 使用Stream API来简化代码,提高可读性和可维护性。
下面是对代码的优化改进:
```
private List<String> v51dkJsonToBinList(List<LightGroupReq> lightGroupReqs) {
LinkedHashMap<Long, List<Frames>> groupingFrames = jsonToBinPub(lightGroupReqs, VehicleConstants.VEHICLE_009);
List<String> result = new ArrayList<>();
Map<Integer, Frames> portMap = new HashMap<>();
List<Frames> frameList = new ArrayList<>();
for (int i = 1; i <= 41; i++) {
frameList.add(new Frames(255, 255, 2550, 2550, 255, 255, 0, i, 0, 2));
}
groupingFrames.put((long) groupingFrames.size(), frameList);
long timeStamp = 0;
int[] temp = new int[42];
Arrays.fill(temp, -1);
for (Map.Entry<Long, List<Frames>> entry : groupingFrames.entrySet()) {
List<Frames> framesList = entry.getValue();
framesList.stream()
.mapToInt(Frames::getGroupIndex)
.forEach(index -> temp[index] = 1);
IntStream.range(1, temp.length)
.filter(index -> temp[index] == -1)
.forEach(index -> portMap.put(index, new Frames(255, 255, 2550, 2550, 255, 255, 0, index, 0, 2)));
framesList.addAll(portMap.values());
framesList = framesList.stream()
.sorted(Comparator.comparing(Frames::getGroupIndex))
.collect(Collectors.toList());
portMap.clear();
if (timeStamp > 7) {
timeStamp = 0;
}
StringBuilder sb = new StringBuilder();
framesList.forEach(frame -> sb.append(BinaryFileUtils.V51DKFramesToHex(frame, frame.getGroupIndex(), timeStamp)));
result.add(sb.toString());
timeStamp++;
}
return result;
}
```
阅读全文