java - how to print values for multiple keys in a hashmap? -
this question has answer here:
- hashmap: 1 key, multiple values 9 answers
i have hashmap hold k,v this:
hashmap<string, string> total=new hashmap<>(); this how im populating map:(in loop result of db table)
total.put(rs.getstring("id"), rs.getstring("name")); now, keys have multiple values, want print each key: key , value. this:
123 john 123 tom 123 jack 234 terry 234 jeniffer 345 jacob 555 sara how can please?
thanks
hashmap (and, in fact, classes implementing map) stores 1 value per key.
quoting javadoc of map:
an object maps keys values. map cannot contain duplicate keys; each key can map @ 1 value.
to store "multiple" values per key, need value type able store multiple values, e.g. collection list or set, map type might map<string, list<string>>.
it's little bit clumsy manage: have check if there collection associated key, add empty 1 if not, , add collection:
// instead of: map.put(key, value); // ...you'd need like: if (!map.containskey(key)) { map.put(key, new arraylist<string>()); } map.get(key).add(value); alternatively, there libraries guava provide multimap, more describe directly.
Comments
Post a Comment