# 集合的实用技巧

作者:Ethan.Yang
博客:https://blog.ethanyang.cn (opens new window)


# 一、集合工具类概览

  • java.util.Collections(JDK 工具类)
  • java.util.Arrays(数组转集合)
  • java.util.stream.Collectors(Stream 收集器)
  • 第三方工具类:
    • Guava 的 Lists、Sets、Maps
    • Apache Commons Collections
    • Hutool 中 CollUtil

# 二、常用集合操作技巧

技巧 方法示例 说明
集合快速初始化 Arrays.asList()List.of()Set.of() 注意返回的是不可变集合或固定长度集合
List<String> list1 = Arrays.asList("A", "B", "C");  // 固定长度,不能增删元素
List<String> list2 = List.of("X", "Y", "Z");        // 不可变集合,添加、删除都会报错
Set<String> set = Set.of("apple", "banana");
1
2
3
技巧 方法示例 说明
集合去重 new HashSet<>(list)distinct()
List<String> list = Arrays.asList("A", "B", "A", "C");
Set<String> set = new HashSet<>(list); // 去重,元素无序

List<String> distinctList = list.stream()
    .distinct()
    .collect(Collectors.toList());
1
2
3
4
5
6
技巧 方法示例 说明
集合不可变 Collections.unmodifiableList(list)List.copyOf() 防止被修改
List<String> original = new ArrayList<>(List.of("A", "B", "C"));
List<String> unmodifiableList = Collections.unmodifiableList(original);
// unmodifiableList.add("D"); // 抛异常 UnsupportedOperationException

List<String> copyList = List.copyOf(original); // Java 10+
1
2
3
4
5
技巧 方法示例 说明
集合排序 Collections.sort()list.sort() 自然排序与自定义 Comparator
List<String> list = new ArrayList<>(List.of("B", "A", "C"));
Collections.sort(list);  // 按自然顺序排序

list.sort(Comparator.reverseOrder()); // 自定义逆序排序
1
2
3
4
技巧 方法示例 说明
集合反转 Collections.reverse(list)
Collections.reverse(list);
1
技巧 方法示例 说明
集合打乱 Collections.shuffle(list) 洗牌算法
Collections.shuffle(list);
1
技巧 方法示例 说明
最大/最小值 Collections.max() / Collections.min()
String max = Collections.max(list);
String min = Collections.min(list);
1
2
技巧 方法示例 说明
二分查找 Collections.binarySearch(sortedList, target) 需要先排序
Collections.sort(list);
int index = Collections.binarySearch(list, "B");
1
2
技巧 方法示例 说明
频率统计 Collections.frequency(list, "X")
int freq = Collections.frequency(list, "A"); // 统计元素"A"出现次数
1

# 二、集合转换实用场景

  • 数组 ↔ 集合
String[] arr = {"A", "B", "C"};
List<String> list = Arrays.asList(arr);

String[] arr2 = list.toArray(new String[0]);
1
2
3
4
  • List ↔ Set
List<String> list = new ArrayList<>(List.of("A", "B", "A"));
Set<String> set = new HashSet<>(list); // 去重无序

List<String> list2 = new ArrayList<>(set); // 转回List
1
2
3
4
  • List ↔ Map
class User {
    private String id;
    private String name;
    private String type;
    // constructor/getters/setters
}

List<User> users = List.of(
    new User("1", "Alice", "admin"),
    new User("2", "Bob", "user")
);

// 转为Map,key为id,value为User对象
Map<String, User> userMap = users.stream()
    .collect(Collectors.toMap(User::getId, Function.identity()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 三、Stream 与 Collectors 常用组合技

  • groupingBy 分组统计
Map<String, List<User>> groupByType = users.stream()
    .collect(Collectors.groupingBy(User::getType));
1
2
  • partitioningBy 二值划分
Map<Boolean, List<User>> partitioned = users.stream()
    .collect(Collectors.partitioningBy(u -> u.getType().equals("admin")));
1
2
  • joining() 字符串拼接
String names = users.stream()
    .map(User::getName)
    .collect(Collectors.joining(", ", "[", "]")); // [Alice, Bob]
1
2
3
  • mapping() 属性映射
List<String> names = users.stream()
    .collect(Collectors.mapping(User::getName, Collectors.toList()));
1
2
  • toMap() 自定义合并函数解决 key 冲突
Map<String, String> map = users.stream()
    .collect(Collectors.toMap(
        User::getType,
        User::getName,
        (name1, name2) -> name1 + ";" + name2));
1
2
3
4
5

# 四、第三方库补强技巧

# Guava 的集合工具

List<String> guavaList = com.google.common.collect.Lists.newArrayList("A", "B", "C");

com.google.common.collect.Multimap<String, String> multimap = com.google.common.collect.ArrayListMultimap.create();
multimap.put("fruit", "apple");
multimap.put("fruit", "banana");

// 不可变集合
List<String> immutableList = com.google.common.collect.ImmutableList.of("X", "Y");
1
2
3
4
5
6
7
8

# Hutool 的 CollUtil

List<String> list1 = List.of("A", "B", "C");
List<String> list2 = List.of("B", "C", "D");

// 判断是否为空
boolean empty = cn.hutool.core.collection.CollUtil.isEmpty(list1);

// 交集
List<String> intersection = cn.hutool.core.collection.CollUtil.intersection(list1, list2);

// 并集
List<String> union = cn.hutool.core.collection.CollUtil.union(list1, list2);

// 差集
List<String> disjunction = cn.hutool.core.collection.CollUtil.disjunction(list1, list2);

// 分割集合
List<List<String>> parts = cn.hutool.core.collection.CollUtil.split(list1, 2);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17