0

How do I print out the corresponding key of the value in that map? I don't think there's a getKey() method for a HashMap.

 Map <Integer, String > map1 = new HashMap <Integer, String> ();
         map1.put(7,"GREAT");
          map1.put(8,"Try Again!");

          if (map1.containsValue("GREAT")){        
             System.out.println(WHAT DO I PUT HERE?);

          }   
halfer
  • 19,824
  • 17
  • 99
  • 186
lolian
  • 15
  • 6
  • Here is answer. http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value – Yubaraj Nov 06 '14 at 11:26
  • 1
    Don't. Fix your program so the map is the right way around. (If you still really want to do it, then you have to do it the boring way by looping over every entry in the map and checking the value.) – user253751 Nov 06 '14 at 11:27
  • @immibis Thanks! That's what i did. Sometimes, just need a simple advise. – lolian Nov 06 '14 at 12:07
  • 1
    @Yubi Thanks, I read that as well. helpful. – lolian Nov 06 '14 at 12:08

1 Answers1

0

Try This:

 Map <Integer, String > map1 = new HashMap <Integer, String> ();
     map1.put(7,"GREAT");
      map1.put(8,"Try Again!");
      Integer key=null;
      Set<Integer>keySet=new HashSet<Integer>();
      if (map1.containsValue("GREAT")){        
        keySet=map1.keySet();
        Iterator<Integer>iter=keySet.iterator();
        while(iter.hasNext()){
            if(map1.get(key=iter.next()).equals("GREAT")){
                break;
            }
        }

      }
      System.out.println("Key is:"+key);
    } 
AsSiDe
  • 1,826
  • 2
  • 15
  • 24