我需要在同一个键中加总值而不仅仅是替换?谢谢。
LinkedHashMap<String, LinkedHashMap<String, Integer>> users = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
String[] input = scanner.readLine().split("\\s+");
String ip = input[0];
String name = input[1];
int duration = Integer.parseInt(input[2]);
if (!users.containsKey(name)) {
users.put(name, new LinkedHashMap<>());
users.get(name).put(ip,duration);
} else {
users.get(name).put(ip,duration);
}
}
您可以在外部地图中使用Map.computeIfAbsent
,并在内部地图中使用Map.merge
:
Map<String, Map<String, Integer>> users = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
String[] input = scanner.readLine().split("\\s+");
String ip = input[0];
String name = input[1];
int duration = Integer.parseInt(input[2]);
users.computeIfAbsent(name, k -> new LinkedHashMap<>())
.merge(ip, duration, Integer::sum);
}
我相信这是你的答案试试这个:
for (int i = 0; i < n; i++) {
String[] input = scanner.readLine().split("\\s+");
String ip = input[0];
String name = input[1];
int duration = Integer.parseInt(input[2]);
if (!users.containsKey(name)) {
users.put(name, new LinkedHashMap<>());
users.get(name).put(ip, duration);
} else {
LinkedHashMap<String, Integer> user = users.get(name);
Integer userDuration = user.get(ip);
user.put(ip, userDuration + duration);
}
}
LinkedHashMap<String, LinkedHashMap<String, Integer>> users = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
String[] input = scanner.readLine().split("\\s+");
String ip = input[0];
String name = input[1];
int duration = Integer.parseInt(input[2]);
LinkedHashMap<String, Integer> ipDurations= users.get(name);
if (ipDurations== null) {
ipDurations= new LinkedHashMap<>();
ipDurations.put(ip, duration);
users.put(name, ipDurations);
} else {
Integer cummulativeDurration = ipDurations.get(ip);
if (cummulativeDurration == null) {
cuumulativeDurration = 0;
ipDurations.put(ip, cummulativeDuration);
}
cummulativeDurration += durration;
}
}
不幸的是我无法添加完整的片段,因为我从手机输入,但我相信所有你需要的是流和收集合并,如果你以后需要初始地图,或只是合并而不是如果你不
int oldDuration = users.get(name).get(ip);
int totalDuration = oldDuration + duration;
users.get(name).put(ip, totalDuration);