Pergunta

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

Foi útil?

Solução

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.

Outras dicas

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:

  • 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

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top