【问题标题】:Merge two maps with same keys in java and add the value together [closed]在java中合并两个具有相同键的映射并将值加在一起[关闭]
【发布时间】:2021-01-28 21:30:22
【问题描述】:

我有这样的数据:

a 0020
b 0010
c 0030
c 0400
a 0100

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

a 0120
b 0010
c 0430

我检索数据的字符串示例: SSSSSSSSSSSSSSSSSSSSS0020 // 它与实际数据不同,但代码是实际的。 我使用 A 是键和 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();
}

谢谢

【问题讨论】:

  • 你试过了吗?发布您的代码。
  • 既然你知道如何put()一个键/值对,并且你知道如何get()一个键的值,并且大概知道如何使用+加法运算符,那么是否阻止您获取任何现有值、添加两个数字并将更新后的值放回去?
  • 那么你有一张地图还是几张地图?您如何使用HashMap 从“对”中检索值?你如何表示这些对,它们是在输入时作为列表/数组提供的,你会显示一些代码吗?
  • SSSSSSSSSSSSSSS00200A000000000000 我使用子字符串来获取 A 作为键和 00200 作为值。然后我使用 hashmap 来打印它们。现在我必须根据键来组织它们并增加总价值。 Map col = new HashMap();尝试 { File file = new File("文件地址.txt");扫描仪 cmd = 新的扫描仪(文件); char entryType = 'A';字符串数 = "";字符串名称 = "";
  • while (cmd.hasNextLine()) { String line = cmd.nextLine(); if (line.charAt(9) == entryType) { num = line.substring(23, 28);名称 = line.substring(29, 34); col.put(名称,数字);迭代器 it2 = col.entrySet().iterator(); while (it2.hasNext()) { Entry entry = (Entry) it2.next(); System.out.println("name = " + entry.getKey() + " and valuem= " + entry.getValue()); }}} 捕获(异常 e){ e.printStackTrace(); }

标签: java collections hashmap


【解决方案1】:

col 映射中的值应该是数字类型以允许算术运算,或者应该创建另一个映射Map&lt;String, Integer&gt; 来存储计算结果。

另外,在读取数据时不需要嵌套循环来计算总和,因为计算结果会不正确。

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

  1. 使用方法Map::compute
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. 使用方法 Map::mergeInteger::sum 可以替换为 lambda (sum, val)-&gt; 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】:

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

    【讨论】:

    • 谢谢,问题是我使用子字符串来检索数据作为键和值。当我使用整数时,它会给我错误。我将代码放在注释中。很抱歉这是我第一次,我可能会错过。大声笑
    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多