天天看點

Java中Map和Set

文章目錄

    • Map和Set
    • Map 的使用
    • Map.Entry

Map和Set

一般把搜尋的資料稱為關鍵字(Key),和關鍵字對應的稱為值(Value),是以模型會有兩種:

  1. 純 key 模型,即 Set 要解決的事情,隻需要判斷關鍵字在不在集合中即可,沒有關聯的 value;
  2. Key-Value 模型,即 Map 要解決的事情,需要根據指定 Key 找到關聯的 Value。

Map 的使用

Map的官方文檔

Java中Map和Set

Map.Entry<K, V>

Map 中定義的 K 類型的 key 和 V 類型的 value 的映射關系的類。

Java中Map和Set

Map常見方法

Java中Map和Set

Map的方法使用

import java.util.HashMap;
import java.util.Map;

public class TestDemo {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "hello");
       // key重複
        map.put(1, "Hello");
        map.put(3, "Java");
        map.put(2, "ABX");
        System.out.println(map);
        // 根據key取得value
        System.out.println(map.get(2));
        // 查找不到傳回null
        System.out.println(map.get(99));
         // 列印所有的 key
        for (Integer key : map.keySet()) {
            System.out.println(key);
        }
        // 列印所有的 value
        for (String value : map.values()) {
            System.out.println(value);
        }
       // 按 key-value 映射關系列印
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}
           

Set 的使用

Set的官方文檔

Set 常見方法

Java中Map和Set

Set的方法使用

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class TestDemo {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("Hello");
        // 重複元素
        set.add("Hello");
        set.add("Abx");
        set.add("Hello");
        set.add("Java");
        int a[] = {5, 3, 4, 1, 7, 8, 2, 6, 0, 9};
        System.out.println(set);
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}