第 15 章:Collections 工具类与常用技巧
学习目标
- 掌握 Collections 工具类的常用方法
- 学会集合与数组的互转
一、Collections 工具类
java.util.Collections 提供一堆静态方法操作集合:
java
List<Integer> list = new ArrayList<>(List.of(3, 1, 4, 1, 5, 9, 2, 6));
Collections.sort(list); // 排序(自然顺序)
Collections.reverse(list); // 反转
Collections.shuffle(list); // 随机打乱
Collections.max(list); // 最大值
Collections.min(list); // 最小值
Collections.frequency(list, 1); // 元素出现次数
Collections.replaceAll(list, 1, 100); // 替换所有
// 线程安全包装(简单的 synchronized 包装,性能一般)
List<Integer> safeList = Collections.synchronizedList(list);按自定义规则排序:
java
List<String> names = new ArrayList<>(List.of("Bob", "Alice", "Charlie"));
names.sort((a, b) -> a.length() - b.length()); // 按字符串长度排
// [Bob, Alice, Charlie]二、数组与集合互转
java
// 数组 → List
String[] arr = {"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(arr)); // 可变 List
// 数组 → Set(自动去重)
Set<String> set = new HashSet<>(Arrays.asList(arr));
// List → 数组
String[] newArr = list.toArray(new String[0]);⚠️ 坑 1:
Arrays.asList(arr)返回的是固定大小 List,不能 add/remove,必须new ArrayList<>(...)包一层。
⚠️ 坑 2:
list.toArray()返回Object[],需要强转;用list.toArray(new String[0])指定类型。
三、List/Set/Map 选型速查
| 场景 | 推荐 |
|---|---|
| 有序、可重复、随机访问 | ArrayList |
| 频繁插入删除两端 | LinkedList(或 ArrayDeque) |
| 去重、无序 | HashSet |
| 去重、保留插入顺序 | LinkedHashSet |
| 自动排序 | TreeSet |
| 键值对、快速查找 | HashMap |
| 键值对、保留插入顺序 | LinkedHashMap |
| 键值对、自动排序 | TreeMap |
| 多线程并发 | ConcurrentHashMap |
四、不可变集合(JDK 9+)
java
List<String> list = List.of("a", "b", "c"); // 不可变 List
Set<String> set = Set.of("a", "b", "c"); // 不可变 Set
Map<String, Integer> map = Map.of("a", 1, "b", 2); // 不可变 Map⚠️ 坑 3:
List.of()/Set.of()/Map.of()都是不可变,任何修改操作抛UnsupportedOperationException。和Arrays.asList()一样,不能 add/remove。
五、实战:工具方法集合
java
public class CollectionUtils {
private CollectionUtils() { } // 工具类禁止实例化
public static <T> List<T> deduplicate(List<T> list) {
return new ArrayList<>(new LinkedHashSet<>(list)); // 保序去重
}
public static <K, V> Map<K, V> filter(Map<K, V> map, Predicate<V> p) {
Map<K, V> result = new LinkedHashMap<>();
map.forEach((k, v) -> {
if (p.test(v)) result.put(k, v);
});
return result;
}
}六、本章小结
| 要点 | 关键 |
|---|---|
| Collections | 静态工具类,排序/反转/最大/最小等 |
| 数组 → List | new ArrayList<>(Arrays.asList(arr)) |
| List → 数组 | list.toArray(new String[0]) |
| 不可变集合 | List.of() / Set.of() / Map.of(),JDK 9+ |
| 选型原则 | 默认 ArrayList + HashMap,要线程安全用 ConcurrentHashMap |
动手练习
- 集合工具方法:写
CollectionUtils.max(List),返回最大值 - 按字符串长度排序:用 sort + Comparator 排序
List<String> - 统计字符频次:用 Map 统计一段文本中每个单词出现的次数
下一章:第 16 章:异常处理 →