java - How to create a new HashMap whenever a duplicate key is found? -
i have txt file containing many records, each record has 5 rows , name-value pairs.
i have parsed file , put names , values hashmap using scanner detect if file hasnextline.
at point because records in same txt file, hashmap contains last record in file. because duplicate keys comes overwrite value key.
my question how create new hashmap each record? method have build 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 : record.keyset()){ system.out.println(i + "\t" + record.get(i)); } }
if understand question correctly, have text file:
name1:value1 name2:value2 name3:value3 name4:value4 name5:value5 name1:value6 name2:value7 name3:value8 name4:value9 name5:value10 etc -- name1-5 repeat, possibly different values
so have conceptually collection objects, each of set of 5 name/value pairs, , objective load of them memory. have 2 choices:
- a
map<string,map<string,string>>
- use if each group of 5 name/value pairs contains within unique key (maybe value associatedname1
, instance) can used differentiate sets. - a
list<map<string,string>>
- use if groups not have unique key, , file linear collection of such sets of name/value pairs.
here's example of first option; adapting second left exercise:
string firstkey = "name1"; map<string,map<string,string>> recordset = new hashmap<string,hashmap<string,string>>(); map<string,string> record = null; string key = null; 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]", ""); if (firstkey.equals(name)) { if (record != null) recordset.put(key,record); record = new hashmap<string,string>(); key = rvalue; } if (record == null) throw new runtimeexception(string.format("first line not '%s'",firstkey)); record.put(rname,rvalue); } catch(exception e){ /* not ignore exceptions */ } if (record != null) recordset.put(key,record); }
Comments
Post a Comment