Collections工具类用法

Collections并不是一个存储数据的一个结构,而是一个为其他数据结构提供一些有效操作函数的工具类

1.Collections的排序操作

复制代码
 1 public static void CollectionsTest1()
 2     {
 3         Comparator com = new Comparator<Integer>(){
 4             public int compare(Integer i1,Integer i2)
 5             {
 6                 return -(i1 - i2);
 7             }
 8         };
 9         
10         List<Integer> list = new ArrayList<>();
11         list.add(5);
12         list.add(3);
13         list.add(2);
14         list.add(1);
15         list.add(4);
16         System.out.println(list);
17         
18         Collections.reverse(list);//反转集合中的元素
19         System.out.println(list);
20         Collections.shuffle(list);//对集合中的元素进行随机排序(即取一个随机情况,每次运行的结果都不一样)
21         System.out.println(list);
22         Collections.sort(list);//对集合中元素进行升序排序
23         System.out.println(list);
24         Collections.sort(list,com);//根据引入的比较器规则来
25         System.out.println(list);
26         Collections.swap(list, 0, 4);//将List中下标为0和下标为4的元素互换
27         System.out.println(list);
28     }
复制代码

 

2.Collections的查找替换操作

复制代码
 1 public static void CollectionsTest2()
 2     {
 3         Comparator<Integer> com = new Comparator<Integer>() {
 4             public int compare(Integer i1,Integer i2)
 5             {
 6                 return -(i1 - i2);
 7             }
 8         };
 9         
10         List<Integer> list = new ArrayList<>();
11         list.add(5);
12         list.add(2);
13         list.add(1);
14         list.add(2);
15         
16         Integer max1 = Collections.max(list);//获取list集合中的最大值
17         System.out.println(max1);
18         Integer max2 = Collections.max(list,com);//通过改变比较器来得到最小值(一般用于要重定义比较器的变量类型)
19         System.out.println(max2);
20         
21         Integer min1 = Collections.min(list);
22         System.out.println(min1);
23         
24         int times = Collections.frequency(list, 2);
25         System.out.println(times);
26         
27         List<Integer> destList = new ArrayList<>();
28         destList.add(0);
29         destList.add(0);
30         destList.add(0);
31         destList.add(0);
32         destList.add(0);
33         
34         Collections.copy(destList, list);//将list中的值全部赋到destList中(一定要保证destList的空间>=List的空间)
35                                          //>的话也只会输出List中的所有元素,而不会把destList中多出来的元素输出
36         System.out.println(list);
37         
38         Collections.replaceAll(list, 2, 3);//将List中所有的2替换为3(此处2是Object而不是Index)
39         System.out.println(list);
40     }
复制代码

 

posted @   jue1e0  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
点击右上角即可分享
微信分享提示