Java Collections 工具類別

java.util.Collections 提供操作集合的靜態工具方法,包括排序、搜尋、同步化等。

引入套件

import java.util.Collections;

排序

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

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

// 反向排序
Collections.sort(list, Collections.reverseOrder());
System.out.println(list);  // [9, 5, 4, 3, 1, 1]

// 自訂排序
Collections.sort(list, (a, b) -> b - a);

搜尋

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

// 二分搜尋(需要已排序)
int index = Collections.binarySearch(list, 3);  // 2
int notFound = Collections.binarySearch(list, 6);  // 負數

// 最大最小
int max = Collections.max(list);  // 5
int min = Collections.min(list);  // 1

反轉與洗牌

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

// 反轉
Collections.reverse(list);
System.out.println(list);  // [5, 4, 3, 2, 1]

// 洗牌
Collections.shuffle(list);
System.out.println(list);  // 隨機順序

// 指定亂數種子
Collections.shuffle(list, new Random(42));

替換與填充

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "A", "C"));

// 全部替換
Collections.replaceAll(list, "A", "X");
System.out.println(list);  // [X, B, X, C]

// 填充
Collections.fill(list, "Z");
System.out.println(list);  // [Z, Z, Z, Z]

旋轉與交換

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

// 旋轉
Collections.rotate(list, 2);
System.out.println(list);  // [4, 5, 1, 2, 3]

// 交換
Collections.swap(list, 0, 4);
System.out.println(list);  // [3, 5, 1, 2, 4]

建立不可變集合

// 空集合
List<String> emptyList = Collections.emptyList();
Set<String> emptySet = Collections.emptySet();
Map<String, Integer> emptyMap = Collections.emptyMap();

// 單一元素
List<String> singletonList = Collections.singletonList("A");
Set<String> singletonSet = Collections.singleton("A");
Map<String, Integer> singletonMap = Collections.singletonMap("key", 1);

// 不可修改的包裝
List<String> unmodifiable = Collections.unmodifiableList(list);
// unmodifiable.add("X");  // 拋出 UnsupportedOperationException

同步化包裝

// 執行緒安全的集合
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 item : syncList) {
        System.out.println(item);
    }
}

頻率與子集

List<String> list = Arrays.asList("A", "B", "A", "C", "A");

// 計算頻率
int freq = Collections.frequency(list, "A");  // 3

// 檢查是否有交集
List<String> other = Arrays.asList("X", "Y", "Z");
boolean disjoint = Collections.disjoint(list, other);  // true(無交集)

複製

List<String> source = Arrays.asList("A", "B", "C");
List<String> dest = new ArrayList<>(Arrays.asList("", "", ""));  // 必須足夠大

Collections.copy(dest, source);
System.out.println(dest);  // [A, B, C]

// 複製 n 份
List<String> copies = new ArrayList<>(Collections.nCopies(5, "X"));
System.out.println(copies);  // [X, X, X, X, X]

實用範例

取得前 N 大元素

public static <T extends Comparable<T>> List<T> topN(List<T> list, int n) {
    List<T> copy = new ArrayList<>(list);
    Collections.sort(copy, Collections.reverseOrder());
    return copy.subList(0, Math.min(n, copy.size()));
}

List<Integer> nums = Arrays.asList(5, 2, 8, 1, 9, 3);
System.out.println(topN(nums, 3));  // [9, 8, 5]

安全的列表操作

public static <T> T getOrDefault(List<T> list, int index, T defaultValue) {
    if (index < 0 || index >= list.size()) {
        return defaultValue;
    }
    return list.get(index);
}

重點整理

  • Collections 提供集合的靜態工具方法
  • 排序:sort(),搜尋:binarySearch()(需已排序)
  • shuffle() 洗牌,reverse() 反轉
  • unmodifiableXxx() 建立不可修改的視圖
  • synchronizedXxx() 建立執行緒安全的包裝
  • emptyXxx()singletonXxx() 建立特殊集合