Java HashMap

HashMap 的键值操作、遍历方式、getOrDefault 与扩容机制。

Beginner
Key PointsHashMap 键唯一、无序,允许一个 null 键;取不存在的键返回 null,用 getOrDefault 给默认值更安全。

创建与存取

put(k, v) stores and returns the previous value (or null), get(k) reads and remove(k) deletes. Reusing a key overwrites the value.

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

public class HashMapBasic {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();

        System.out.println(map.put("a", 1));
        System.out.println(map.put("a", 2));
        System.out.println(map.get("a"));
        System.out.println(map.get("z"));
        System.out.println(map.size());
    }
}
Output
null
1
2
null
1

安全取值

getOrDefault(k, def) removes null checks, containsKey tests presence and putIfAbsent writes only when absent. These three shorten a lot of code.

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

public class HashMapSafe {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("a", 1);

        System.out.println(map.getOrDefault("a", 0));
        System.out.println(map.getOrDefault("b", 0));
        System.out.println(map.containsKey("a"));

        map.putIfAbsent("a", 99);
        map.putIfAbsent("b", 2);
        // HashMap 的遍历顺序由哈希桶决定,不能依赖;要断言内容就按键取值
        System.out.println(map.size() + " entries: a=" + map.get("a") + ", b=" + map.get("b"));
    }
}
Output
1
0
true
2 entries: a=1, b=2

遍历 HashMap

Three ways to iterate: entrySet() for pairs (most common), keySet() for keys and values() for values. To delete while iterating use an Iterator or removeIf.

HashMap makes no ordering promise — iteration follows the hash buckets. The example uses LinkedHashMap (insertion order) so the output is reproducible; use TreeMap when you need key ordering.
Java
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class HashMapIter {
    public static void main(String[] args) {
        Map<String, Integer> map = new LinkedHashMap<>();   // 保留插入顺序
        map.put("b", 2);
        map.put("a", 1);

        for (Map.Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + "=" + e.getValue());
        }

        System.out.println(new TreeMap<>(map));   // 按 key 排序后输出
        System.out.println(map.values());         // 仍是插入顺序
    }
}
Output
b=2
a=1
{a=1, b=2}
[2, 1]

HashMap 方法

put, get, remove, size, isEmpty, containsKey, containsValue, keySet, values, entrySet, merge, compute. Default capacity is 16 with a 0.75 load factor; exceeding it doubles the table.

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

public class HashMapMethods {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();

        map.merge("a", 1, Integer::sum);
        map.merge("a", 1, Integer::sum);
        map.compute("b", (k, v) -> v == null ? 10 : v + 1);

        System.out.println(map);
        System.out.println(map.containsKey("a"));
        System.out.println(map.containsValue(10));

        map.remove("a");
        System.out.println(map);
    }
}
Output
{a=2, b=10}
true
true
{b=10}

Friends & Partners