Collections工具类
Collections
Java ⾥关于集合的 ⼯具类,包含有各种有关集合操作的静态多态 ⽅法,不能实例化(把构造函 数私有化)。
Collection 与 Collections 区别
- Collection 是接 ⼝,提供了对集合对象进 ⾏基本操作的通 ⽤接 ⼝ ⽅法,List、Set 等多种具体的 实现类。
- Collections 是 ⼯具类,专 ⻔操作 Collection 接 ⼝实现类 ⾥ ⾯的元素。
常见方法
排序
1@Test
2 public void collectionsIteratorTesting() {
3 ArrayList<String> list = new ArrayList<>();
4 list.add("bbb");
5 list.add("aaa");
6 list.add("ccc");
7 System.out.println(list);////不指定排序,默认按照自然升序排序 [aaa, bbb, ccc]
8 Collections.sort(list,Comparator.naturalOrder()); //升序 [aaa, bbb, ccc]
9 Collections.sort(list,Comparator.reverseOrder()); //降序 [ccc, bbb, aaa]
10 Collections.shuffle(list);//随机排序
11 System.out.println(list);
12 }
获取最值 max/min
1//初始化容器
2 ArrayList<Student> list = new ArrayList<>();
3 list.add(new Student("a",15));
4 list.add(new Student("b",18));
5 list.add(new Student("c",12));
6
7 //获取最大元素
8 Student maxStudent = Collections.max(list, new Comparator<Student>() {
9 @Override
10 public int compare(Student o1, Student o2) {
11 return o1.getAge() - o2.getAge();
12 }
13 });
14 System.out.println(maxStudent);//Student(name=b, age=18)
15
16 //获取最小元素
17 Student minStudent = Collections.min(list, new Comparator<Student>() {
18 @Override
19 public int compare(Student o1, Student o2) {
20 return o1.getAge() - o2.getAge();
21 }
22 });
23 System.out.println(minStudent);//Student(name=c, age=12)
24 }
创建不可变集合
1public void collectionsUnmodifiableTesting() {
2 //创建不可变集合List
3 List<String> list = new ArrayList<>();
4 list.add("a");
5 list.add("b");
6 list.add("c");
7 list = Collections.unmodifiableList(list);
8
9 //创建不可变集合Set
10 Set<String> set = new HashSet<>();
11 set.add("a");
12 set.add("b");
13 set.add("c");
14 set = Collections.unmodifiableSet(set);
15
16 //创建不可变Map
17 Map<String, String> map = new HashMap<>();
18 map.put("a", "jack");
19 map.put("b", "alice");
20 map.put("c", "Tom");
21 map = Collections.unmodifiableMap(map);
22 }