A Hashmap only has one value for each key, so this will not be possible. You would need a Multimap for this (as in Guava for example), or a Map to a List of values.
Retrieve individual entries of hashmap with same key
题
I have created a Hashmap which has multiple entries for a single Key entry. Now I want to retrieve all values individually. How can I do this?
I have checked many sites but couldn't get a clue on how to implement it, and an example code snippet can be useful for me.
HashMap<String,String>
key value
04302014 04302014
04302014 abc
04302014 10
04302014 20
04302014 20
05302014 05302014
05302014 def
05302014 10
05302014 20
05302014 20
Now using the key
I want to retrieve all values individually and store in variables.
Like for key 04302014
I need to extract once and store in variables and in second iteration for the key 05302014
.
解决方案
其他提示
any map (hashmap,linkedhashmap ,hashtable or treemap) in java can have only one unique key.
if you add same key again then it overrides the previous key.
so better to add values in a list or set and add that to map using single key.
same is demonstrated as below
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> values1 = new ArrayList<String>();
List<String> values2 = new ArrayList<String>();
values1.add("10");
values1.add("20");
values2.add("30");
values2.add("40");
map.put("key1", values1);
map.put("key2", values2);
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println(entry.getKey() + " values are ");
System.out.println(entry.getValue());
}
in your case create list with the values 04302014,abc,10,20,20
another list with values def,10,20,20
add these two list with corresponding key key 04302014 for list1 and key 05302014 for list2