【发布时间】: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