Java中Map的多种用法

1. 创建:5 种一行写法

java 复制代码
// ① 传统
Map<String, Integer> map = new HashMap<>();

// ② 不可变(JDK 9+)
Map<String, Integer> map = Map.of("a", 1, "b", 2);

// ③ 函数式(JDK 8+)
Map<String, Integer> map = Stream.of(new Object[][]{{"a", 1}, {"b", 2}})
                                 .collect(Collectors.toMap(o -> (String) o[0], o -> (Integer) o[1]));

// ④ Guava 可变
Map<String, Integer> map = Maps.newHashMap();

// ⑤ Guava 不可变
Map<String, Integer> map = ImmutableMap.of("a", 1, "b", 2);

2. 读写:日常 API

java 复制代码
map.put("k", 1);                 // 存
map.get("k");                    // 取
map.getOrDefault("k", 0);        // 防 NPE
map.remove("k");                 // 删
map.containsKey("k");            // 判断
map.size();                      // 大小

3. 遍历:4 种姿势

java 复制代码
// ① entrySet(最快)
for (Map.Entry<String, Integer> e : map.entrySet()) {
    System.out.println(e.getKey() + "=" + e.getValue());
}

// ② Java 8 Lambda
map.forEach((k, v) -> System.out.println(k + "=" + v));

// ③ keySet
for (String k : map.keySet()) {
    System.out.println(k + "=" + map.get(k));
}

// ④ Stream
map.entrySet().stream()
              .filter(e -> e.getValue() > 10)
              .forEach(e -> System.out.println(e.getKey()));

4. 计算型 Map:merge / compute

java 复制代码
// 计数器:单词出现次数
map.merge(word, 1, Integer::sum);

// 累加:key 对应的值 + delta
map.compute(key, (k, v) -> v == null ? delta : v + delta);

5. 线程安全:3 种锁策略

java 复制代码
// ① 全表锁(慢)
Map<String, Integer> map = new Hashtable<>();

// ② 分段锁(快)
Map<String, Integer> map = new ConcurrentHashMap<>();

// ③ 不可变(无锁)
Map<String, Integer> map = ImmutableMap.of("a", 1);

6. 顺序 Map:3 种有序实现

java 复制代码
// ① 插入顺序
Map<String, Integer> map = new LinkedHashMap<>();

// ② 访问顺序(LRU)
Map<String, Integer> map = new LinkedHashMap<>(16, 0.75f, true);

// ③ 排序顺序
Map<String, Integer> map = new TreeMap<>();   // 自然序
Map<String, Integer> map = new TreeMap<>(Comparator.reverseOrder()); // 倒序

7. 空值友好:Optional 链

java 复制代码
String name = Optional.ofNullable(map.get("k"))
                      .map(String::valueOf)
                      .orElse("");

8. 黑科技:Map 当作函数缓存

java 复制代码
Map<String, Function<Integer, Integer>> funcMap = Map.of(
        "square", x -> x * x,
        "cube", x -> x * x * x
);

int result = funcMap.getOrDefault("square", x -> x).apply(5); // 25

9. 一行记忆

"HashMap 日常,LinkedHashMap 顺序,TreeMap 排序,ConcurrentHashMap 并发,ImmutableMap 只读,merge 计数,Optional 防空!"

相关推荐
Bruce_Liuxiaowei1 分钟前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
IT_陈寒6 分钟前
Java线程池用错参数,我的服务居然悄悄崩溃了
前端·人工智能·后端
滕州市燕猫虎计算机科技工作室个体工商户8 分钟前
IDEA:Command line is too long
java·ide·intellij-idea
做运维的阿瑞9 分钟前
Python 标准库汇总:分类速览与常用模块清单
linux·运维·python
why-geo14 分钟前
Hermes Agent 与 Python 的会产生什么样的碰撞
人工智能·python·ai编程
卡布鲁21 分钟前
React useMemo 与 useCallback 完全指南:原理、场景与避坑
前端·react.js
正经教主22 分钟前
【FDE系列】阶段2:Day 29:FastAPI 进阶 — Pydantic 模型与完整 CRUD 实战
人工智能·python·fde
gCode Teacher 格码致知26 分钟前
Pandas教学-6:coerce详解
python·pandas
梦在远山后30 分钟前
Electron 与 FastAPI 如何完成流式 Agent 对话
python·langchain·agent
碳基修炼37 分钟前
排查记:本地 devServer 是 http,浏览器却把 302 重定向升级成了 https
前端·http