private List<String> efJsonToBinList(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 <= 48; 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[49]; //全部初始化为-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.efFramesToHex(framesList.get(j),framesList.get(j).getGroupIndex(),timeStamp)); } timeStamp++; } return list; }优化此段代码
时间: 2024-01-20 22:02:06 浏览: 70
HashMap<K,V>对象-java教程第六版
首先,可以将数组初始化部分的代码优化为使用Java 8的IntStream来进行初始化。
其次,对于portMap的初始化和添加部分,可以使用Java 8的Stream API中的filter和map方法来实现,可以简化代码。
最后,对于framesList的排序部分,可以使用Collections.sort方法代替stream中的sorted方法,因为stream中的sorted方法需要创建一个新的List对象,而Collections.sort方法可以直接对原List进行排序。
优化后的代码如下:
```
private List<String> efJsonToBinList(List<LightGroupReq> lightGroupReqs) {
LinkedHashMap<Long, List<Frames>> groupingFrames = jsonToBinPub(lightGroupReqs, VehicleConstants.VEHICLE_009);
List<String> list = new ArrayList<>();
Map<Integer, Frames> portMap = new HashMap<>();
List<Frames> frameList = new ArrayList<>();
IntStream.rangeClosed(1, 48).forEach(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[49];
Arrays.fill(temp, -1);
framesList.forEach(f -> temp[f.getGroupIndex()] = 1);
portMap = IntStream.rangeClosed(1, temp.length - 1)
.filter(i -> temp[i] == -1)
.mapToObj(i -> new Frames(255, 255, 2550, 2550, 255, 255, 0, i, 0, 2))
.collect(Collectors.toMap(Frames::getGroupIndex, f -> f, (a, b) -> a, HashMap::new));
framesList.addAll(portMap.values());
Collections.sort(framesList, Comparator.comparing(Frames::getGroupIndex));
portMap.clear();
if (timeStamp > 7) {
timeStamp = 0;
}
framesList.forEach(f -> list.add(BinaryFileUtils.efFramesToHex(f, f.getGroupIndex(), timeStamp)));
timeStamp++;
}
return list;
}
```
阅读全文