欢迎访问宙启技术站
智能推送

了解Java中Collections函数的常见操作

发布时间:2023-06-18 19:27:47

Collections是Java中的一个工具类,提供了大量的常用方法来简化对集合的操作,提高了代码的可读性和复用性。本文将介绍Java中Collections函数的常见操作。

1. 创建集合

使用Collections的静态方法可以方便地创建各种类型的集合,如List、Set、Map等,例如:

List<String> list = Collections.emptyList();
Set<Integer> set = Collections.singleton(1);
Map<String, Integer> map = Collections.emptyMap();

2. 集合排序

Collections的sort()方法可以对List集合进行排序,也可以利用Comparator自定义排序规则,例如:

List<Integer> list = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3);
Collections.sort(list); // [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
Collections.sort(list, Collections.reverseOrder()); // [9, 6, 5, 5, 4, 3, 3, 2, 1, 1]
Collections.sort(list, (x,y) -> x % 5 - y % 5); // [5, 5, 1, 1, 6, 2, 3, 9, 4, 3]

3. 集合元素查找

Collections的binarySearch()方法可以在有序的List中查找元素,也可以利用Comparator自定义查找规则,例如:

List<Integer> list = Arrays.asList(1, 2, 3, 3, 4, 5, 5, 6, 9);
int index = Collections.binarySearch(list, 5); // 5
index = Collections.binarySearch(list, 7); // -8
index = Collections.binarySearch(list, 7, (x,y) -> x - y); // -9

4. 集合反转

Collections的reverse()方法可以将List集合反转,例如:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Collections.reverse(list); // [5, 4, 3, 2, 1]

5. 集合元素替换

Collections的replaceAll()方法可以将List集合中的某个元素替换为另一个元素,例如:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Collections.replaceAll(list, 3, 9); // [1, 2, 9, 4, 5]

6. 集合元素填充

Collections的fill()方法可以将List集合中的所有元素替换为指定元素,例如:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Collections.fill(list, 0); // [0, 0, 0, 0, 0]

7. 集合最值查找

Collections的max()和min()方法可以在List集合中查找最大和最小值,例如:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int max = Collections.max(list); // 5
int min = Collections.min(list); // 1

8. 集合随机置换

Collections的shuffle()方法可以对List集合进行随机置换,例如:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Collections.shuffle(list); // [2, 1, 4, 5, 3]

9. 集合不可修改

Collections的unmodifiableXXX()方法可以将List、Set、Map集合变为不可修改的,例如:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> unmodifiableList = Collections.unmodifiableList(list);
Set<Integer> unmodifiableSet = Collections.unmodifiableSet(new HashSet<>(list));
Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(Map.of("one", 1, "two", 2, "three", 3));

10. 集合同步化

Collections的synchronizedXXX()方法可以将List、Set、Map集合变为线程安全的,例如:

List<Integer> list = new ArrayList<>();
List<Integer> synchronizedList = Collections.synchronizedList(list);
Set<Integer> synchronizedSet = Collections.synchronizedSet(new HashSet<>());
Map<String, Integer> synchronizedMap = Collections.synchronizedMap(new HashMap<>());

总之,Collections是Java中一个非常实用的工具类,拥有许多常见操作,使用它可以对集合进行简单和快速的操作,提高代码编写的效率和可读性。