I have the following entries in my HashMap
<key1,value1>
<key2,value2>
<key3,value2>
<key4,value4>
<key5,value2>
I would like to find all the Keys that contain the value "value2". The answer would be a KeySet containing the following keys: {key2,key3,key4}
Is it possible to accomplish that in a HashMap? thanks
Map is supposed to use in such way that access the values using the keys, but it seems you are doing it in reverse.
If you are sure about what you are doing, there is no good way to accomplish. Iterate over map and store the keys in separate list.
More over Look at Gauva's Multimap , that might suits for your requirment.
I would like to find all the Keys that contain the value "value2". The answer would be a KeySet containing the following keys: {key2,key3,key4}
Two options:
just Iterate entries of your map and check if the value of the current entry is equal to "value2" then add it to Set. try this
Set<String> keySet = new HashSet<String>();
for (Map.Entry<String, String> entry : map.entrySet())
{
if(entry.getValue().equals("value2")
{
keySet.add(entry.getKey());
}
}
I guess there is no other option since you have duplicate values in your map.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.