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 防空!"

相关推荐
hello 早上好6 分钟前
03_JVM(Java Virtual Machine)的生命周期
java·开发语言·jvm
言無咎17 分钟前
从规则引擎到任务规划:AI Agent 重构跨境财税复杂账务处理体系
大数据·人工智能·python·重构
张小凡vip22 分钟前
数据挖掘(十)---python操作Spark常用命令
python·数据挖掘·spark
夕除24 分钟前
js--7
java
布谷歌28 分钟前
面试题整理
java·开发语言
U盘失踪了29 分钟前
Reqable 导出响应数据
python
2401_8590490833 分钟前
git submodule update --init --recursive无法拉取解决
前端·chrome·git
2301_7903009633 分钟前
数据分析与科学计算
jvm·数据库·python
爬山算法35 分钟前
Hibernate(74)如何在CQRS架构中使用Hibernate?
java·架构·hibernate
jjjava2.044 分钟前
深入解析Set与Map的奥秘
java·开发语言