如何获取该HashMap中值的相应键?

时间:2014-11-06 11:24:58

标签: java dictionary key

如何打印该地图中值的相应键?我不认为这是HashMap的getKey()方法。

 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?);

          }   

1 个答案:

答案 0 :(得分:0)

试试这个:

 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);
    }