优化这段代码 public static List<Map<String, String>> getConnectParamMapList(String connectParamsStr) { String[] split01 = StringUtils.split(connectParamsStr, '&'); LinkedList<Map<String, String>> resultList = new LinkedList<>(); for (String s : split01) { String[] split02 = StringUtils.split(s, '='); String connectParamName = split02[0]; String connectParamValue = split02[1]; Map<String, String> connectParamMap = new HashMap<>(); connectParamMap.put(connectParamName, connectParamValue); resultList.add(connectParamMap); } return resultList; }
时间: 2023-05-20 16:06:07 浏览: 137
'); List<Map<String, String>> connectParamMapList = new ArrayList<>();
for (String s : split01) {
String[] split02 = StringUtils.split(s, ',');
Map<String, String> connectParamMap = new HashMap<>();
for (String s1 : split02) {
String[] split03 = StringUtils.split(s1, '=');
connectParamMap.put(split03[0], split03[1]);
}
connectParamMapList.add(connectParamMap);
}
return connectParamMapList;
}
可以使用 Java 8 的 Stream API 来简化代码,如下所示:
public static List<Map<String, String>> getConnectParamMapList(String connectParamsStr) {
return Arrays.stream(connectParamsStr.split("\\r?\\n"))
.map(s -> Arrays.stream(s.split(","))
.map(s1 -> s1.split("="))
.collect(Collectors.toMap(s2 -> s2[0], s2 -> s2[1])))
.collect(Collectors.toList());
}
阅读全文