如何在相同的密钥HashMap Java中加总值?

问题描述 投票:1回答:5

我需要在同一个键中加总值而不仅仅是替换?谢谢。

    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);
        }
    }
java hashmap
5个回答
3
投票

您可以在外部地图中使用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);
}

2
投票

我相信这是你的答案试试这个:

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);
        }
    }

2
投票
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;
          }
     }

1
投票

不幸的是我无法添加完整的片段,因为我从手机输入,但我相信所有你需要的是流和收集合并,如果你以后需要初始地图,或只是合并而不是如果你不


0
投票
int oldDuration = users.get(name).get(ip);
int totalDuration = oldDuration + duration;
users.get(name).put(ip, totalDuration);
© www.soinside.com 2019 - 2024. All rights reserved.