Java基礎 HashMap的添加 修改 遍歷 Map.Entry Map.entrySet()的使用及實例

Java Map

Map中不能包含相同的鍵,每個鍵只能映射一個值。

HashMap:並不能保證它的元素的順序,元素加入散列映射的順序並不一定是它們被迭代方法讀出的順序。

  • Map.Entry

Map.Entry 是Map中的一個接口,他的用途是表示一個映射項(裏面有Key和Value)

Map.Entry裏有相應的getKey和getValue方法,即JavaBean,讓我們能夠從一個項中取出Key和Value。

  • Map.entrySet()

Map.entrySet() 這個方法返回的是一個Set<Map.Entry<K,V>>。Set裏面的類型是Map.Entry,裏面存放的是鍵值對。一個K對應一個V。

  • Map.keyset()

keySet是鍵的集合,Set裏面的類型即key的類型。

package Map.test;


import java.util.*;

public class Test {
	public static void main(String args[]) {
		// 創建HashMap 對象
		HashMap hm = new HashMap();
		// 加入元素到HashMap 中
		hm.put("John Doe", new Double(3434.34));
		hm.put("Tom Smith", new Double(123.22));
		hm.put("Jane Baker", new Double(1378.00));
		hm.put("Todd Hall", new Double(99.22));
		hm.put("Ralph Smith", new Double(-19.08));
		// 返回包含映射項的集合
		Set set = hm.entrySet();
		// 用Iterator 得到HashMap 中的內容
		Iterator i = set.iterator();
		// 顯示元素
		while (i.hasNext()) {
			// Map.Entry 可以操作映射的輸入
			Map.Entry me = (Map.Entry) i.next();
			System.out.print(me.getKey() + ": ");
			System.out.println(me.getValue());
		}
		System.out.println();
		// 讓John Doe 中的值增加1000
		double balance = ((Double) hm.get("John Doe")).doubleValue();//得到舊值
		// 用新的值替換舊的值
		hm.put("John Doe", new Double(balance + 1000));
		System.out.println("John Doe's 現在的資金:" + hm.get("John Doe"));
	}
}
/*
Todd Hall: 99.22
John Doe: 3434.34
Ralph Smith: -19.08
Tom Smith: 123.22
Jane Baker: 1378.0

John Doe's 現在的資金:4434.34
*/

//四種遍歷Map
public static void main(String[] args) {
 
    Map<String, String> map = new HashMap<String, String>();
    map.put("1", "value1");
    map.put("2", "value2");
    map.put("3", "value3");
  
    //第一種:普遍使用,二次取值
    System.out.println("通過Map.keySet遍歷key和value:");
    for (String key : map.keySet()) {
        System.out.println("key= "+ key + " and value= " + map.get(key));
    }
  
    //第二種
    System.out.println("通過Map.entrySet使用iterator遍歷key和value:");
    Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> entry = it.next();
        System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    }
  
    //第三種:推薦,尤其是容量大時
    System.out.println("通過Map.entrySet遍歷key和value");
    for (Map.Entry<String, String> entry : map.entrySet()) {
        System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    }
 
    //第四種
    System.out.println("通過Map.values()遍歷所有的value,但不能遍歷key");
    for (String v : map.values()) {
        System.out.println("value= " + v);
    }
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章