java - How to store more than one value for same key in HashMap? -
i have string named inputrow
, looks this:
1,kit,23 2,ret,211
i apply regex (.+),(.+),(.+)
on , store results in multiple variables.
for first line 1,kit,23
get:
inputrow.1-->1 inputrow.2-->kit inputrow.3-->23
for second line 2,ret,211
get:
inputrow.1-->2 inputrow.2-->ret inputrow.3-->211
i want store input rows in hashmap
same key inputrow
. how can in java?
my java code is..,
line="1,kit,23"; final map<string, string> regexresults = new hashmap<>(); pattern pattern = pattern.compile("(.+),(.+),(.+)"); final matcher matcher = pattern.matcher(line); if (matcher.find()) { final string basekey = "inputrow"; (int = 0; <= matcher.groupcount(); i++) { final string key = new stringbuilder(basekey).append(".").append(i).tostring(); string value = matcher.group(i); if (value != null) { regexresults.put(key, value); } }
now wants store second row in "regexresults" process.how possible?
create class inputrow
:
class inputrow { private int value1; private string value2; private int value3; //...getters , setters }
and hashmap<integer, list<inputrow>>
. hash map key row index , assign matching rows list<inputrow>
hash map.
for clarification, hashmap
stores one entry one unique key. therefore, cannot assign more 1 entry same key or else entry overwritten. so, need write container cover multiple objects or use existing list
.
example code
i used both of text fragments, separated newline character, 2 lines. snippet puts 2 inputrow
objects in list hashmap
key "inputrow". note, matcher group index starts @ 1
, 0 refers whole group. mind simplicity assumed created inputrow(string, string, string)
constructor.
string line = "1,kit,23\n2,ret,211"; final map<string, list<inputrow>> regexresults = new hashmap<>(); pattern pattern = pattern.compile("(.+),(.+),(.+)"); final matcher matcher = pattern.matcher(line); list<inputrow> entry = new arraylist<>(); while (matcher.find()) { entry.add(new inputrow(matcher.group(1), matcher.group(2), matcher.group(3))); } regexresults.put("inputrow", entry);
Comments
Post a Comment