优化这段代码 ArrayList<String> stnCodeList = new ArrayList<>(Arrays.asList("1020C", "1021C", "1135C", "1136C" , "1137C", "1138C", "1139C" , "1140C" , "1141C" , "1142C" , "1143C" , "1144C" , "1145C" , "1147C" , "1149C" , "1221C" , "1222C" , "1223C" , "1224C","1146C","1119C","1148C")); @GetMapping("stn") public CommonResult airStation(){ HttpResponse response = HttpRequest.get(Constants.SMALL_AIR_STATION).execute(); List<AirStationVo> data = new ArrayList<>(); try { if (response.getStatus() == HttpStatus.HTTP_OK) { String body = response.body(); CommonResult commonResult = JSONUtil.toBean(body, CommonResult.class); List<JSONObject> airStationVos = (List)commonResult.getData(); for (String value : stnCodeList) { for (JSONObject stationVo : airStationVos) { AirStationVo airStationVo = JSONUtil.toBean(stationVo, AirStationVo.class); String stnCode = airStationVo.getStnCode(); String s = value; if (s.equals(stnCode)) { data.add(airStationVo); } } } } }catch (Exception e) { e.printStackTrace(); return CommonResult.failed(e.getMessage()); } return CommonResult.success(data,"成功"); }
时间: 2024-02-14 18:09:02 浏览: 77
首先,可以将 `stnCodeList` 改为 `Set<String>` 类型,这样查找元素的时间复杂度会更低。其次,可以使用流式 API 来简化代码并提高效率。修改后的代码如下:
```
Set<String> stnCodeSet = new HashSet<>(Arrays.asList("1020C", "1021C", "1135C", "1136C", "1137C", "1138C", "1139C", "1140C", "1141C", "1142C", "1143C", "1144C", "1145C", "1147C", "1149C", "1221C", "1222C", "1223C", "1224C", "1146C", "1119C", "1148C"));
@GetMapping("stn")
public CommonResult airStation() {
HttpResponse response = HttpRequest.get(Constants.SMALL_AIR_STATION).execute();
try {
if (response.getStatus() == HttpStatus.HTTP_OK) {
String body = response.body();
CommonResult commonResult = JSONUtil.toBean(body, CommonResult.class);
List<JSONObject> airStationVos = (List)commonResult.getData();
List<AirStationVo> data = airStationVos.stream()
.map(stationVo -> JSONUtil.toBean(stationVo, AirStationVo.class))
.filter(station -> stnCodeSet.contains(station.getStnCode()))
.collect(Collectors.toList());
return CommonResult.success(data, "成功");
}
} catch (Exception e) {
e.printStackTrace();
return CommonResult.failed(e.getMessage());
}
return CommonResult.failed("请求失败");
}
```
使用流式 API 可以简化代码并提高效率。同时,将 `stnCodeList` 改为 `Set<String>` 类型,可以提高查找元素的效率。
阅读全文