Skip to content
清晨的一缕阳光
返回

Collections 工具类详解

Collections 工具类详解

Collections 是 Java 集合框架的工具类,提供了丰富的静态方法来操作集合。

一、排序操作

1.1 sort

List<Integer> list = Arrays.asList(3, 1, 4, 1, 5);

// 自然排序
Collections.sort(list);
// [1, 1, 3, 4, 5]

// 自定义排序
Collections.sort(list, (a, b) -> b - a);
// [5, 4, 3, 1, 1]

// Java 8:List 自带 sort
list.sort(Comparator.naturalOrder());

1.2 shuffle

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// 随机打乱
Collections.shuffle(list);

// 指定随机源
Collections.shuffle(list, new Random(42));

1.3 reverse

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

// 反转
Collections.reverse(list);
// [5, 4, 3, 2, 1]

1.4 swap

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// 交换元素
Collections.swap(list, 0, 4);
// [5, 2, 3, 4, 1]

1.5 rotate

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// 旋转(距离为正向右旋转)
Collections.rotate(list, 2);
// [4, 5, 1, 2, 3]

// 距离为负向左旋转
Collections.rotate(list, -2);
// [3, 4, 5, 1, 2]

二、查找操作

2.1 binarySearch

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// 二分查找(要求已排序)
int index = Collections.binarySearch(list, 3);
// 2

// 未找到返回负数
int notFound = Collections.binarySearch(list, 6);
// -6(插入点 -1)

// 自定义比较器
int index = Collections.binarySearch(list, 3, Comparator.naturalOrder());

2.2 max / min

List<Integer> list = Arrays.asList(3, 1, 4, 1, 5);

// 最大值
Integer max = Collections.max(list);
// 5

// 最小值
Integer min = Collections.min(list);
// 1

// 自定义比较器
String maxStr = Collections.max(Arrays.asList("a", "bb", "ccc"), 
    Comparator.comparingInt(String::length));
// "ccc"

2.3 frequency

List<Integer> list = Arrays.asList(1, 2, 2, 3, 2);

// 元素出现次数
int count = Collections.frequency(list, 2);
// 3

2.4 disjoint

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);
List<Integer> list3 = Arrays.asList(3, 4, 5);

// 是否没有交集
boolean result1 = Collections.disjoint(list1, list2); // true
boolean result2 = Collections.disjoint(list1, list3); // false

三、填充与替换

3.1 fill

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// 填充指定值
Collections.fill(list, 0);
// [0, 0, 0, 0, 0]

3.2 replaceAll

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 2, 3, 2));

// 替换所有匹配元素
Collections.replaceAll(list, 2, 9);
// [1, 9, 9, 3, 9]

3.3 copy

List<Integer> src = Arrays.asList(1, 2, 3);
List<Integer> dest = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0));

// 复制(目标列表必须足够大)
Collections.copy(dest, src);
// [1, 2, 3, 0, 0]

3.4 nCopies

// 不可变列表,包含 n 个指定元素
List<String> list = Collections.nCopies(5, "Hello");
// [Hello, Hello, Hello, Hello, Hello]

// 初始化固定值列表
List<Integer> scores = new ArrayList<>(Collections.nCopies(10, 0));

四、同步包装

4.1 synchronizedCollection

// 线程安全的集合
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
Set<String> syncSet = Collections.synchronizedSet(new HashSet<>());
Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());

// 遍历时需要手动同步
synchronized (syncList) {
    for (String s : syncList) {
        System.out.println(s);
    }
}

4.2 使用建议

// ❌ 不安全
List<String> list = new ArrayList<>();
// 多线程访问

// ✅ 使用同步包装
List<String> list = Collections.synchronizedList(new ArrayList<>());

// ✅ 使用并发包
List<String> list = new CopyOnWriteArrayList<>();

// ✅ 使用 Stream
List<String> list = Collections.synchronizedList(new ArrayList<>());
list.parallelStream().forEach(System.out::println);

五、不可变集合

5.1 unmodifiable 方法

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> unmodifiable = Collections.unmodifiableList(list);

// ❌ 抛异常
unmodifiable.add("d"); // UnsupportedOperationException

// 注意:原列表仍可修改
list.add("d");
// unmodifiable 也会变化

5.2 Java 9+ 集合工厂

// 不可变列表
List<String> list = List.of("a", "b", "c");

// 不可变集合
Set<String> set = Set.of("a", "b", "c");

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

// 注意:不可修改
list.add("d"); // UnsupportedOperationException

六、Arrays 工具类

6.1 排序

int[] arr = {3, 1, 4, 1, 5};

// 排序
Arrays.sort(arr);
// [1, 1, 3, 4, 5]

// 范围排序
Arrays.sort(arr, 1, 4);
// [1, 1, 3, 4, 5]

// 对象数组自定义排序
String[] strs = {"ccc", "a", "bb"};
Arrays.sort(strs, Comparator.comparingInt(String::length));

6.2 查找

int[] arr = {1, 2, 3, 4, 5};

// 二分查找(要求已排序)
int index = Arrays.binarySearch(arr, 3);
// 2

// 范围查找
int index = Arrays.binarySearch(arr, 1, 4, 3);

6.3 填充

int[] arr = new int[5];

// 填充
Arrays.fill(arr, 10);
// [10, 10, 10, 10, 10]

// 范围填充
Arrays.fill(arr, 1, 4, 0);
// [10, 0, 0, 0, 10]

6.4 复制

int[] arr = {1, 2, 3, 4, 5};

// 复制
int[] copy = Arrays.copyOf(arr, arr.length);

// 扩容
int[] larger = Arrays.copyOf(arr, 10);

// 范围复制
int[] sub = Arrays.copyOfRange(arr, 1, 4);
// [2, 3, 4]

6.5 比较

int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
int[] arr3 = {1, 2, 4};

// 比较
boolean equal = Arrays.equals(arr1, arr2); // true
boolean notEqual = Arrays.equals(arr1, arr3); // false

// 范围比较
boolean rangeEqual = Arrays.equals(arr1, 0, 2, arr2, 0, 2);

6.6 toString

int[] arr = {1, 2, 3};

// 转字符串
String str = Arrays.toString(arr);
// "[1, 2, 3]"

// 二维数组
int[][] arr2d = {{1, 2}, {3, 4}};
String str2d = Arrays.deepToString(arr2d);
// "[[1, 2], [3, 4]]"

七、实用技巧

7.1 列表转 Map

List<String> list = Arrays.asList("a", "bb", "ccc");

// 转 Map(key 为字符串,value 为长度)
Map<String, Integer> map = list.stream()
    .collect(Collectors.toMap(
        s -> s,
        String::length
    ));

7.2 去重

List<String> list = Arrays.asList("a", "b", "a", "c", "b");

// 去重
List<String> unique = list.stream()
    .distinct()
    .collect(Collectors.toList());

// 或使用 Set
List<String> unique = new ArrayList<>(new HashSet<>(list));

7.3 合并列表

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);

// 合并
List<Integer> merged = new ArrayList<>(list1);
merged.addAll(list2);

// 或使用 Stream
List<Integer> merged = Stream.concat(list1.stream(), list2.stream())
    .collect(Collectors.toList());

7.4 空列表优化

// ✅ 使用空列表
List<String> empty = Collections.emptyList();

// ✅ 单元素列表
List<String> single = Collections.singletonList("one");

// ✅ Java 9+
List<String> empty = List.of();
List<String> single = List.of("one");

八、总结

Collections 核心方法:

类型方法说明
排序sort, shuffle, reverse, rotate列表重排
查找binarySearch, max, min, frequency元素查找
填充fill, replaceAll, copy, nCopies批量操作
同步synchronizedList/Set/Map线程安全
不可变unmodifiableList/Set/Map只读集合

Collections 提供了丰富的集合操作方法,掌握它们能大幅提高编码效率。


分享这篇文章到:

上一篇文章
MySQL 分布式事务解决方案
下一篇文章
MySQL 锁优化与并发控制