I have a txt file containing many records, each record has 5 rows and are name-value pairs.
I have parsed the file and put the names and values into a hashmap by using a scanner to detect if the file hasNextLine.
At this point because all the records are in the same txt file, the hashmap only contains the last record in the file. This is because the any duplicate keys that comes up will overwrite the value for that key.
My question is how to create a new hashmap for each record?
This is the method i have to build the records:
public void recordBuilder() throws FileNotFoundException{
FileReader reader = new FileReader(aFile);
Scanner outerScan = new Scanner(reader);
HashMap<String,String> record = new HashMap<String,String>();
while (outerScan.hasNextLine()){
Scanner innerScan = new Scanner(outerScan.nextLine());
try{
innerScan.useDelimiter(":");
String name = innerScan.next();
String value = innerScan.next();
String rName = name.trim();
String rValue = value.replaceAll("[^\\w]", "");
record.put(rName,rValue);
}
catch(Exception e){
}
}
for(String i : record.keySet()){
System.out.println(i + "\t" + record.get(i));
}
}
If I understand your question correctly, you have a text file:
So what you have conceptually is a collection objects, each of which is a set of five name/value pairs, and your objective is to load all of them into memory. You have two choices:
Map<String,Map<String,String>>– Use this if each group of five name/value pairs contains within it a unique key (maybe the value associated withname1, for instance) that can be used to differentiate the sets.List<Map<String,String>>– Use this if the groups do not have a unique key, and the file is just a linear collection of such sets of name/value pairs.Here’s an example of the first option; adapting it for the second is left as an exercise: