帮我优化一下下面的代码: public class TestController { public static void main(String[] args) { String textA = "开发,总监:张三,李四"; String textB = "运维,总监:张三,王五"; String textC = "开发,运维:王五,李四"; List<String> textList = new ArrayList<>(Arrays.asList(textA,textB,textC)); Map<String,Set<String>> result = new HashMap<>(); for (String text : textList) { String[] split = text.split(":"); String[] positions = split[0].split(","); String[] users = split[1].split(","); for (String position : positions) { Set<String> list = result.get(position); if (list == null){ Set<String> userResult = new HashSet<>(); for (String user : users) { userResult.add(user); } result.put(position,userResult); }else { for (String user : users) { list.add(user); } } } } System.out.println(result); } }
时间: 2024-02-14 19:06:39 浏览: 106
以下是代码优化后的结果:
```java
public class TestController {
public static void main(String[] args) {
String textA = "开发,总监:张三,李四";
String textB = "运维,总监:张三,王五";
String textC = "开发,运维:王五,李四";
List<String> textList = Arrays.asList(textA, textB, textC);
Map<String, Set<String>> result = new HashMap<>();
for (String text : textList) {
String[] split = text.split(":");
String[] positions = split[0].split(",");
String[] users = split[1].split(",");
for (String position : positions) {
result.computeIfAbsent(position, k -> new HashSet<>()).addAll(Arrays.asList(users));
}
}
System.out.println(result);
}
}
```
优化点如下:
1. 将 `ArrayList` 改为 `Arrays.asList`,利用 `Arrays.asList` 生成的列表可以进行快速的初始化,且不需要额外的内存空间。
2. 将 `if (list == null)` 改为 `result.computeIfAbsent(position, k -> new HashSet<>())`,利用 `computeIfAbsent` 方法可以快速的获得键对应的值,如果值不存在,则会新建一个值并返回。
3. 将 `for (String user : users) { list.add(user); }` 改为 `result.get(position).addAll(Arrays.asList(users));`,利用 `addAll` 方法可以快速地添加一个集合的所有元素。
阅读全文