简体   繁体   English

如何在Hashmap中返回特定值的键?

[英]How can i return the keys of a specific value in Hashmap?

I have the following entries in my HashMap 我的HashMap中有以下条目

<key1,value1>
<key2,value2>
<key3,value2>
<key4,value4>
<key5,value2>

I would like to find all the Keys that contain the value "value2". 我想找到所有包含值“ value2”的键。 The answer would be a KeySet containing the following keys: {key2,key3,key4} 答案是一个包含以下键的KeySet:{key2,key3,key4}

Is it possible to accomplish that in a HashMap? 是否有可能在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. Map应该以通过键访问值的方式使用,但似乎您是在反向进行。

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. 详细了解Gauva的Multimap ,它可能适合您的要求。

I would like to find all the Keys that contain the value "value2". 我想找到所有包含值“ value2”的键。 The answer would be a KeySet containing the following keys: {key2,key3,key4} 答案是一个包含以下键的KeySet:{key2,key3,key4}

Two options: 两种选择:

  • new map where the values are the keys and the keys are the values (if every key and value are unique) 新地图,其中值是键,键是值(如果每个键和值都是唯一的)
  • iterate through the entries of your map and check if the value of the current entry is equal to "value2", if yes add it a set with the results 遍历地图的条目,并检查当前条目的值是否等于“ value2”,如果是,则将其与结果集一起添加

just Iterate entries of your map and check if the value of the current entry is equal to "value2" then add it to Set. 只是迭代地图的条目,并检查当前条目的值是否等于“ value2”,然后将其添加到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. 我猜没有其他选择,因为您的地图中有重复的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM