1. 三大常用 Map 区别
- HashMap
- 无序、键唯一、线程不安全
- 允许
null键 1 个,多个null值 - 底层:数组 + 链表 + 红黑树(JDK1.8)
- 默认容量 16,负载因子 0.75,扩容 2 倍
- LinkedHashMap
- 有序(插入顺序),继承 HashMap
- 底层多一条双向链表维护顺序
- TreeMap
- 自然排序(key 升序)
- 底层红黑树,key 必须实现 Comparable
- 不允许 null 键
2. Map 常用方法
map.put(k,v) // 添加/覆盖
map.get(k) // 取值
map.remove(k) // 删除
map.containsKey(k) // 判断键
map.containsValue(v)// 判断值
map.size() // 长度
map.clear() // 清空
map.isEmpty() // 是否为空
3. Map 三种遍历
// 1. 遍历key
for (String k : map.keySet()){}
// 2. 遍历value
for (Integer v : map.values()){}
// 3. 遍历键值对【最优】
for (Map.Entry<K,V> e : map.entrySet()){
e.getKey();
e.getValue();
}
4. Map 简洁写法(JDK8)
map.forEach((k,v)-> System.out.println(k+v));
map.getOrDefault("key",0); // 无key返回默认值
map.putIfAbsent(k,v); // 不存在才添加
二、Stream 流(集合最强操作)
1. 三大步骤
创建流 → 中间操作(链式) → 终止操作
2. 流创建
list.stream() // 集合串行流
list.parallelStream()// 并行流
Stream.of(1,2,3) // 快速创建
3. 常用中间操作(返回流,可链式)
filter(条件):过滤map():类型转换 / 提取字段(最常用)sorted():排序distinct():去重limit(n):取前 n 个skip(n):跳过前 n 个
4. 常用终止操作(关闭流)
forEach():遍历collect():收集成集合最重要count():统计数量max/min():最值anyMatch/allMatch:匹配判断
5. 高频实战代码
// 1. 过滤+收集
List<User> list = users.stream()
.filter(u->u.getAge()>18)
.collect(Collectors.toList());
// 2. map提取字段
List<String> names = users.stream()
.map(User::getName)
.collect(Collectors.toList());
// 3. 排序
list.stream().sorted(Comparator.comparing(User::getAge));
// 4. 分组(Stream转Map)
Map<Integer,List<User>> groupMap = users.stream()
.collect(Collectors.groupingBy(User::getAge));
// 5. 转Map
Map<Long,String> idNameMap = users.stream()
.collect(Collectors.toMap(User::getId,User::getName));
6. Collectors 常用收集
toList()→ ListtoSet()→ 去重 SetgroupingBy()→ 分组 Mapjoining()→ 字符串拼接summingInt()→ 求和averagingInt()→ 求平均
三、Map + Stream 联合用法
// Map遍历转流
map.entrySet().stream()
.filter(e->e.getValue()>100)
.forEach(System.out::println);
// List转Map
List<Student> -> Map<学号,姓名>
list.stream().collect(Collectors.toMap(Student::getId,Student::getName));