public List<String> bxGetExcelList(List<LightGroupReq> lightGroupReqs) { LinkedHashMap<Long, List<Frames>> groupingFrames = jsonToBinPub(lightGroupReqs,VehicleConstants.VEHICLE_X); 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; for (Map.Entry<Long, List<Frames>> entry : groupingFrames.entrySet()) { List<Frames> framesList = entry.getValue(); int[] temp = new int[79]; //全部初始化为-1 Arrays.fill(temp, -1); for (int i = 0; i < framesList.size(); i++) { temp[framesList.get(i).getGroupIndex()] = 1; } // 补充FF 数据帧 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()); 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++) { BinaryFileUtils.bxFramesToHex(framesList.get(j),timeStamp,writeBinList); } timeStamp++; } return writeBinList; }优化这段代码
时间: 2024-02-14 10:13:46 浏览: 56
1. 在for循环中创建的Frames对象可以提取出来,避免重复创建对象,提高效率。
2. 可以将填充-1的数组temp改为使用HashSet或LinkedHashSet,避免重复遍历数组。
3. 可以使用Lambda表达式代替for循环中的操作,简化代码。
4. 可以使用Map的computeIfAbsent方法避免重复判断key是否存在。
重构后的代码如下:
```
public List<String> bxGetExcelList(List<LightGroupReq> lightGroupReqs) {
LinkedHashMap<Long, List<Frames>> groupingFrames = jsonToBinPub(lightGroupReqs,VehicleConstants.VEHICLE_X);
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;
for (Map.Entry<Long, List<Frames>> entry : groupingFrames.entrySet()) {
List<Frames> framesList = entry.getValue();
Set<Integer> groupIndexSet = new HashSet<>();
framesList.forEach(f -> groupIndexSet.add(f.getGroupIndex()));
// 补充FF 数据帧
groupIndexSet.stream()
.filter(i -> !framesList.stream().anyMatch(f -> f.getGroupIndex() == i))
.forEach(i -> portMap.computeIfAbsent(i, k -> new Frames(7, 63, 63, 2550, 15, 15, 0, k, 0, 2)));
framesList.addAll(portMap.values());
framesList.sort(Comparator.comparing(Frames::getGroupIndex));
portMap.clear();
if (timeStamp > 7) {
timeStamp = 0;
}
framesList.forEach(f -> BinaryFileUtils.bxFramesToHex(f, timeStamp, writeBinList));
timeStamp++;
}
return writeBinList;
}
```
阅读全文