gpt4 book ai didi

java - 更新 Java 中嵌套 hashmap 的值

转载 作者:行者123 更新时间:2023-12-01 17:45:42 24 4
gpt4 key购买 nike

我需要根据从文件中获取的值更新嵌套的 HashMap 。我能够从文件中获取正确的值,但只有最后一个值会更新为 HashMap 中的所有 header 值。我的代码错误在哪里?代码如下:

import java.net.*;
import java.io.*;
import java.util.*;

public class ParseMap {
public static void main(String args[]) {
BufferedReader reader;
HashMap<String, HashMap<String, String>> hMap = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> innerMap = new HashMap<String, String>();
String header = "";
try {
reader = new BufferedReader(new FileReader(
"file.txt"));
String line = reader.readLine();
while (line != null) {
if (line.contains("CallMade")) {
String[] words = line.split(",");

for(int i=0; i<words.length; i++) {
if (words[i].startsWith("CallId")) {
header = words[i];
}
}
hMap.put(header, innerMap);
}
else if (line.contains("details") && line.contains(header)) {
String[] words = line.split(",|:");
System.out.println(header);

for(int i=0; i<words.length; i++) {
System.out.println(words[i]);
if (words[i].equals(" Agentdetails")) {

HashMap<String, String> inMap = hMap.get(header);
if (inMap == null) {
hMap.put(header, inMap = new HashMap<>());
}
inMap.put("Agent", words[i+1]);
inMap.put("AgentID", words[i+2]);
}
}
}
line = reader.readLine();
}
reader.close();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(hMap);
}
}

文件.txt

[Call  ] 15:40:35.688 CallMade,Telenet,,CallId53,123456789,5674,02Apr
[CallId53 ] Agentdetails,John,12,21
[Call ] 15:42:39.324 CallMade,Airtel,,CallId54,123456789,5674,02Apr
[CallId54 ] Agentdetails,James,10,20
[Call ] 15:43:39.324 CallMade,Airtel,,CallId55,123456789,5674,02Apr
[Call ] 15:43:40.324 CallMade,Airtel,,CallId56,123456789,5674,02Apr
[CallId55 ] Agentdetails,Jimmy,5,100
[CallId56 ] Agentdetails,Robert,18,120

在这里,如果我打印单词列表的值,那么我会得到正确的值,但如果我在放置值后打印 HashMap ,则只有 AgentAgentId 的最后一个值> 被放入 hashedmap 中的所有 header 。如何纠正错误?提前致谢!

最佳答案

在我看来,您的文本文件结构良好,所有调用详细信息都列在相应的代理详细信息之前,我将推荐如下所示的内容:

public static void main(String[] args) {
BufferedReader reader;
HashMap<String, HashMap<String, String>> hMap = new HashMap<>();
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
if(line.startsWith("[Call ")){
String callId = line.split(",")[3];
hMap.put(callId, new HashMap<>());
}
else if(line.startsWith("[CallId")){
String callId = line.substring(line.indexOf('[')+1, line.indexOf(']')).trim();
hMap.get(callId).put("Agent", line.split(",")[1]);
hMap.get(callId).put("AgentId", line.split(",")[2]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(hMap);
}

关于java - 更新 Java 中嵌套 hashmap 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55569086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com