java-API之集合11——Collections工具类常用方法
常用方法
- static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) 根据元素的自然顺序,返回给定 collection 的最大元素。
- static <T> T min(Collection<? extends T> coll) 根据元素的自然顺序 返回给定 collection 的最小元素。
- static <T extends Comparable<? super T>> void sort(List<T> list) 根据元素的自然顺序 对指定列表按升序进行排序。
- static void reverse(List<?> list) 反转指定列表中元素的顺序。
- static <T> void sort(List<T> list, Comparator<? super T> c) 根据指定比较器产生的顺序对指定列表进行排序。
- static void swap(List<?> list, int i, int j) 在指定列表的指定位置处交换元素。
- static <T> boolean addAll(Collection<? super T> c, T... elements) 将所有指定元素添加到指定 collection 中。
- static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) 根据指定比较器产生的顺序,返回给定 collection 的最大元素。
- static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) 根据指定比较器产生的顺序,返回给定 collection 的最小元素。
测试
1 public class Test_Collections { 2 3 public static void main(String[] args) { 4 5 List<Integer> list = new ArrayList<>(); 6 7 list.add(3); 8 list.add(2); 9 list.add(10); 10 list.add(6); 11 System.out.println(list); // [3, 2, 10, 6] 12 // 根据元素的自然顺序 对指定列表按升序进行排序。 13 Collections.sort(list); 14 System.out.println(list); // [2, 3, 6, 10] 15 16 // 根据元素的自然顺序,返回给定 collection 的最大元素。 17 System.out.println(Collections.max(list)); // 10 18 19 // 根据元素的自然顺序 返回给定 collection 的最小元素。 20 System.out.println(Collections.min(list)); // 2 21 22 // 反转指定列表中元素的顺序。 23 Collections.reverse(list); 24 System.out.println(list); // [10, 6, 3, 2] 25 26 // 在指定列表的指定位置处交换元素。 27 Collections.swap(list, 1, 2); 28 System.out.println(list); // [10, 3, 6, 2] 29 30 } 31 }
sort方法的高级用法——内部类的使用
1 2 3 // 该类测试 Collections 工具类 4 public class Test2_Collections { 5 6 public static void main(String[] args) { 7 8 List<Integer> list = new ArrayList<>(); 9 10 list.add(3); 11 list.add(2); 12 list.add(10); 13 list.add(6); 14 System.out.println(list); // [3, 2, 10, 6] 15 16 // 安装自定义的顺序给元素排序 17 Collections.sort(list, new Comparator<Integer>(){ // 匿名内部类 18 // 重写Comparator接口里的compare()方法 19 @Override 20 public int compare(Integer o1, Integer o2) { 21 // o1 - o2 默认排序方式,从小到大 22 // return o2 - o1; //从大到小 大于0交换位置 23 return o1 - o2; //从小到大 大于0交换位置 24 // return -1; // 当前list进行了反转 25 // return 1; // 返回当前list 26 } 27 }); 28 System.out.println(list); // [2, 3, 6, 10] 29 } 30 }
注:上述代码需要导入相应的包,可自行导入