在 Java HashMap 中獲取與指定鍵關聯的值
使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP