Collections集合
Collections是Java中的一个非常有用的类,它提供了用于操作集合框架(如List,Set,Queue,Deque等)的方法。这个类是Java集合框架的一部分,提供了一种方便的方式来对集合进行各种操作。
以下是Collections类的一些主要功能:
- 排序和搜索: Collections类提供了用于对列表进行排序和搜索的方法。例如,你可以使用sort()方法对列表进行排序,或者使用binarySearch()方法在一个排序的列表中搜索一个元素。
- 随机化: 使用shuffle()方法可以随机排列列表中的元素。
- 数据转换: 你可以使用transform()方法对列表中的每个元素应用一个函数。这可以用于多种数据转换,例如将每个元素乘以一个固定的数。
- 查找和替换: indexOf()和lastIndexOf()方法可以用来查找列表中元素的索引,replaceAll()方法可以用来替换列表中的所有元素,这些方法在处理集合时非常有用。
- 比较和合并: Collections类提供了许多比较集合的方法,例如equals()和hashCode(),以及合并两个集合的方法,如addAll()。
其他操作: 还有一些其他有用的方法,如rotate()(旋转列表),copy()(复制列表),fill()(填充列表),等等。
根据以上演示代码:
1) 排序和搜索
List<Integer> list = new ArrayList<>();
// 批量添加
Collections.addAll(list, 3, 4, 2, 5, 1, 8);
System.out.println("未排序的结果:" + list);
// 使用Collections的sort方法对列表进行排序
Collections.sort(list); // 默认为升序
System.out.println("排序后的结果:" + list);
Collections.sort(list, (o1, o2) -> o2.compareTo(o1)); // 降序
System.out.println("降序:" + list);
Collections.sort(list, (o1, o2) -> o1.compareTo(o2)); // 升序
System.out.println("升序:" + list);
// 使用Collections的binarySearch方法在排序列表中搜索元素
int index = Collections.binarySearch(list, 3);
if(index >= 0) {
System.out.println("元素3在列表所在位置:" + index);
}else {
System.out.println("元素3不在列表中");
}
演示结果:
2)随机化
List<Integer> list = new ArrayList<>();
// 批量添加
Collections.addAll(list, 3, 4, 2, 5, 1, 8);
System.out.println("原始列表:" + list);
// 使用Collections的shuffle方法对列表进行随机排列
Collections.shuffle(list);
System.out.println("随机排列后的列表:" + list);
演示结果:
3)数据转换
没学。。。暂时不会,学了再补充
4) 查找和替换
// 查找
// 创建一个列表
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
// 使用indexOf方法查找元素首次出现的位置
int index = list.indexOf("C");
System.out.println("元素C在列表中的首次出现位置:" + index);
// 使用lastIndexOf方法查找元素最后一次出现的位置
int lastIndex = list.lastIndexOf("C");
System.out.println("元素C在列表中的最后一次出现位置:" + lastIndex);
// 替换
// 创建一个列表
List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry", "date"));
// 使用 Collections 的 forEach 方法以及 lambda 表达式来替换列表中的所有元素
Collections.replaceAll(list, "date", "orange");
// 打印修改后的列表
System.out.println(list);
演示结果:
5)比较
Collection<Integer> col1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collection<Integer> col2 = new ArrayList<>(Arrays.asList(4, 5, 6, 7, 8));
Collection<Integer> col3 = new ArrayList<>(Arrays.asList(4, 5, 6, 7, 8));
// 比较col1和col2是否相等
if(col1.equals(col2) || col1.hashCode() == col2.hashCode()) {
System.out.println("相等");
}else {
System.out.println("不相等");
}
// 比较col2和col3是否相等
if(col2.equals(col3) || col1.hashCode() == col2.hashCode()) {
System.out.println("相等");
}else {
System.out.println("不相等");
}
6)合并
Collection<Integer> col1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collection<Integer> col2 = new ArrayList<>(Arrays.asList(4, 5, 6, 7, 8));
col1.addAll(col2);
System.out.println(col1);