使用get()方法获取与给定键关联的值。
这是我们的HashMap及其元素-
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));获取相关值。键被设置为这样的参数-
hm.get("Frames")上面的键是Frames,我们正在获取与其关联的值。
以下是获取与Java HashMap中的给定键关联的值的示例-
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("The value for key Frames in the HashMap = "+hm.get("Frames"));
   }
}输出结果
Elements in HashMap... Frames: 800 Belt: 600 Wallet: 700 Bag: 1100 Sunglasses: 2000 The value for key Frames in the HashMap = 800