专业的JAVA编程教程与资源

网站首页 > java教程 正文

100个Java工具类之72:强大而灵活的集合工具类Collections

temp10 2025-02-21 15:28:48 java教程 14 ℃ 0 评论

Collections作为一个功能强大的集合工具类,能够极大地简化集合的操作、排序、搜索以及线程安全处理。


100个Java工具类之72:强大而灵活的集合工具类Collections


一、排序与搜索

  1. sort和reverseOrder,用于排序

List numbers = Arrays.asList(5, 3, 8, 1, 2);      
// 自然排序
Collections.sort(numbers);
System.out.println("自然排序: " + numbers);
输出:自然排序: [1, 2, 3, 5, 8]
// 逆序排序
List reversedNumbers = new ArrayList<>(numbers);
Collections.sort(reversedNumbers, Collections.reverseOrder());
System.out.println("逆序排序: " + reversedNumbers);
输出:逆序排序: [8, 5, 3, 2, 1]
  1. 二分查找
List sortedNumbers = Arrays.asList(1, 2, 3, 5, 8);
// 二分查找
int index = Collections.binarySearch(sortedNumbers, 3);
System.out.println("数字3的索引: " + index);
输出:数字3的索引: 2
// 查找不存在的元素
int notFoundIndex = Collections.binarySearch(sortedNumbers, 4);
System.out.println("数字4的索引(负数表示未找到): " + notFoundIndex);
输出:数字4的索引(负数表示未找到): -5



二、排序与搜索

3. 填充与替换

List strings = Arrays.asList("a", "b", "c", "d");
 // 填充集合
Collections.fill(strings, "x");
System.out.println("填充后的集合: " + strings);
输出:填充后的集合: [x, x, x, x]
// 注意:由于Arrays.asList返回的列表是固定大小的,下面的操作会抛出UnsupportedOperationException
// 若要避免此异常,应使用ArrayList等可变大小的列表
List mutableStrings = new ArrayList<>(strings);
// 替换所有"x"为"y"
Collections.replaceAll(mutableStrings, "x", "y");
System.out.println("替换后的集合: " + mutableStrings);
输出:替换后的集合: [y, y, y, y]

4. 集合的最大值与最小值

List scores = Arrays.asList(85.5, 92.0, 78.3, 99.9, 88.6);
// 最大值
Double maxScore = Collections.max(scores);
System.out.println("最高分: " + maxScore);
输出:最高分: 99.9
// 最小值
Double minScore = Collections.min(scores);
System.out.println("最低分: " + minScore);
输出:最低分: 78.3



三、线程安全处理

  1. 同步包装器

将非同步集合包装成同步集合,确保线程安全

List list = new ArrayList<>();
// 创建同步列表
List synchronizedList = Collections.synchronizedList(list);
 // 同步块内操作集合
synchronized (synchronizedList) {
   synchronizedList.add("Hello");
   synchronizedList.add("World");
  }

四、不可变集合

6. 将现有集合转换为不可变集合

// 创建不可变空列表
List emptyList = Collections.emptyList();
System.out.println("不可变空列表: " + emptyList);
输出:不可变空列表: []
// 创建不可变单元素列表
List singletonList = Collections.singletonList("Only One");
System.out.println("不可变单元素列表: " + singletonList);
输出:不可变单元素列表: [Only One]
// 将可变列表转换为不可变列表
List mutableList = new ArrayList<>(Arrays.asList("a", "b", "c"));
List unmodifiableList = Collections.unmodifiableList(mutableList);
System.out.println("不可变列表: " + unmodifiableList);
输出:不可变列表: [a, b, c]        
// 尝试修改不可变列表将抛出UnsupportedOperationException
// unmodifiableList.add("d"); // Uncommenting this line will throw an exception

Collections为集合操作提供了便捷高效的解决方案,合理地使用,能最大程度地是代码更简洁、高效、可维护。


本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表