0

I have a problem finding a key from a specific value.

I know the other way round to find a value from a key but not a key from a value. I think I found quite a lot solutions but I don't really understand them, can you help me please ?

HashMap<Spielfeldposition, Integer> risikoregionen = new HashMap<Spielfeldposition, Integer>(); 
Marged
  • 10,577
  • 10
  • 57
  • 99
ddvdt
  • 1
  • language ? Example of your HashMap ? – Marged Jun 04 '15 at 21:03
  • Java. HashMap risikoregionen = new HashMap(); We want to find the key "Spielfeldposition" by checking the highest value. – ddvdt Jun 04 '15 at 21:07
  • possible duplicate of [Java Hashmap: How to get key from value?](http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value) – djechlin Jun 04 '15 at 21:38

2 Answers2

0

For the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map.

Then you can use entrySet() to get the mappings. Then you can iterate the values and get the corresponding key.

EDIT

Iterator entries = myMap.entrySet().iterator();

while (entries.hasNext()) {

Entry thisEntry = (Entry) entries.next();
Object key;

if(yourvalue == thisEntry.getValue()){
key = thisEntry.getKey();

return key
// ...
}}
XOR-Manik
  • 493
  • 1
  • 4
  • 19
  • ok, can u give us an example pls? Map risikoregionen= for(Spielfeldposition key : map.keySet()) { int value = map.get(key); } like that? – ddvdt Jun 04 '15 at 21:17
0

If you also need to get keys from values, maybe the data structure you need is a bidirectional map. Question #770254, "How to create a 2 way map in java", deals with that.

Community
  • 1
  • 1
bruno
  • 2,213
  • 1
  • 19
  • 31