有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

集合合并java中具有相同键的两个映射,并将值添加到一起

我有这样的数据:

a 0020
b 0010
c 0030
c 0400
a 0100

因为它们是成对的,所以我使用HashMap来检索它们。现在,我必须将它们加在一起,结果应该是一个键,并将值加在一起,如下所示:

a 0120
b 0010
c 0430

我检索数据的字符串示例: SSSSSSSS0020//它与实际数据不同,但代码是实际的。 我使用了一个is键和0020作为值

Map<String, String> col = new HashMap<>();
try {
    File file = new File("file address.txt");
    Scanner cmd = new Scanner(file);
    String num = "";
    String Name = "";

    while (cmd.hasNextLine()) {
        String line = cmd.nextLine();
        if (line.charAt(9) == 'A') {
            num = line.substring(23, 28); 
            Name = line.substring(29, 34);
            col.put(Name, num);     
        }
        Iterator it2 = col.entrySet().iterator();
        while (it2.hasNext()) {
            Entry<String, String> entry = (Entry<String, String>) it2.next();
            System.out.println("name = " + entry.getKey() + " and value= " + entry.getValue());
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

谢谢


共 (2) 个答案

  1. # 1 楼答案

    col映射中的值应为数字类型以允许算术运算,或者应创建另一个映射Map<String, Integer>以存储计算结果

    此外,在读取数据时,不需要使用嵌套循环来计算总和,因为计算结果将不正确

    有几种方法可以累积映射中每个键的和

    1. 使用方法^{}
    Map<String, Integer> col = new HashMap<>(); // changed value type to Integer
    // ...
    Integer number = 0;
    while (cmd.hasNextLine()) {
        String line = cmd.nextLine();
        if (line.charAt(9) == 'A') {
            number = Integer.valueOf(line.substring(23, 28)); 
            Name = line.substring(29, 34);
            col.compute(Name, (key, prev) -> (prev == null ? 0 : prev) + number);     
        }
        // no need for nested loop
    }
    
    // print map contents
    col.forEach((name, sum) -> System.out.print("%s %04d%n", name, sum));
    
    1. 使用方法^{}和可替换为lambda (sum, val)-> sum + val^{}
    Integer number = 0;
    while (cmd.hasNextLine()) {
        String line = cmd.nextLine();
        if (line.charAt(9) == 'A') {
            number = Integer.valueOf(line.substring(23, 28)); 
            Name = line.substring(29, 34);
            col.merge(Name, number, Integer::sum);     
        }
    }
    // print map contents
    col.forEach((name, sum) -> System.out.print("%s %04d%n", name, sum));
    
  2. # 2 楼答案

    在向HashMap添加对时,可以检查密钥是否已经存在,如果已经存在,则只需将HashMap中的值与对中的值求和即可

    HashMap<String, Integer> map = new HashMap<>(); // your HashMap
    String key;                                     // pair key
    int value;                                      // pair value
    
    if(map.keySet().contains(key)) {
        map.put(key, map.get(key) + value);
    } else {
        map.put(key, value);
    }