public String bxJsonTobin(List<LightGroupReq> lightGroupReqs, Integer binHashCode, List<String> lightGroupList) { LinkedHashMap<Long, List<Frames>> groupingFrames = jsonToBinPub(lightGroupReqs, VehicleConstants.VEHICLE_X); ArrayList<String> list = new ArrayList<>(); ArrayList<String> writeBinList = new ArrayList<>(); Map<Integer, Frames> portMap = new HashMap<>(); List<Frames> frameList = new ArrayList<>(); for (int i = 1; i <= 78; i++) { frameList.add(new Frames(7, 63, 63, 2550, 15, 15, 0, i, 0, 2)); } groupingFrames.put((long) groupingFrames.size(), frameList); long timeStamp = 0; int[] temp = new int[79]; Arrays.fill(temp, -1); for (Map.Entry<Long, List<Frames>> entry : groupingFrames.entrySet()) { List<Frames> framesList = entry.getValue(); 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(7, 63, 63, 2550, 15, 15, 0, i, 0, 2)); } } framesList.addAll(portMap.values()); portMap.clear(); framesList = framesList.stream().sorted(Comparator.comparing(Frames::getGroupIndex)).collect(Collectors.toList()); if (timeStamp > 7) { timeStamp = 0; } for (int j = 0; j < framesList.size(); j++) { list.add(BinaryFileUtils.bxFramesToHex(framesList.get(j), timeStamp, writeBinList)); } timeStamp++; Arrays.fill(temp, -1); } return fileService.uploadBin(list, binHashCode); }优化这段代码
时间: 2024-03-17 15:44:34 浏览: 103
Java中List集合对象去重及按属性去重的8种方法
5星 · 资源好评率100%
首先,可以将一些常量抽取出来,避免魔数出现在代码中,增加代码的可读性。例如:
```
private static final int FRAME_COUNT = 78;
private static final int BYTE_COUNT = 7;
private static final int RED = 63;
private static final int GREEN = 63;
private static final int BLUE = 2550;
private static final int BRIGHTNESS = 15;
private static final int SPEED = 15;
private static final int MODE = 2;
```
接下来,可以将一些变量和对象的声明放到使用它们的地方,避免不必要的变量和对象声明,提高代码的可读性和性能。例如:
```
for (Map.Entry<Long, List<Frames>> entry : jsonToBinPub(lightGroupReqs, VehicleConstants.VEHICLE_X).entrySet()) {
int[] temp = new int[FRAME_COUNT + 1];
Arrays.fill(temp, -1);
List<Frames> framesList = entry.getValue();
for (Frames frame : framesList) {
temp[frame.getGroupIndex()] = 1;
}
Map<Integer, Frames> portMap = IntStream.rangeClosed(1, FRAME_COUNT)
.filter(i -> temp[i] == -1)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> new Frames(BYTE_COUNT, RED, GREEN, BLUE, BRIGHTNESS, SPEED, 0, i, 0, MODE)));
framesList.addAll(portMap.values());
framesList.sort(Comparator.comparing(Frames::getGroupIndex));
long timeStamp = entry.getKey() % 8;
for (Frames frame : framesList) {
list.add(BinaryFileUtils.bxFramesToHex(frame, timeStamp, writeBinList));
}
}
```
上述代码中的改进包括:
1. 将 `groupingFrames` 的声明去掉,直接使用 `jsonToBinPub` 的返回值;
2. 将 `temp` 的声明放到了 for 循环里面,减少了不必要的变量声明;
3. 使用 Java 8 中的 Stream API 来生成 `portMap`,增加了代码的可读性;
4. 将 `framesList` 的排序和遍历合并到了一起;
5. 将 `timeStamp` 的计算放到了 for 循环里面,避免了重复计算。
阅读全文