集合(三)集合的工具类Collections

ゞ 浴缸里的玫瑰 2023-10-04 19:16 106阅读 0赞

Collections: 是集合的工具类

1.常用方法:

  1. static <T> boolean addAll(Collection<? super T> c, T... elements)
  2. //把数组的元素添加到集合
  3. static void reverse(List<?> list) //把List集合的元素反转
  4. static void shuffle(List<?> list) //随机打乱List集合元素的顺序
  5. static <T extends Comparable<? super T>>
  6. void sort(List<T> list) //自然排序
  7. static <T> void sort(List<T> list, Comparator<? super T> c) //指定排序

2.应用(例子)

  1. Integer[] arr = new Integer[]{1,3,5,4,2,1};
  2. //把数组的元素添加到集合中
  3. List<Integer> list = new ArrayList<>();
  4. //Collections.addAll()
  5. Collections.addAll(list,arr);
  6. System.out.println(list);
  7. //反转
  8. Collections.reverse(list);
  9. System.out.println(list);
  10. //随机打乱集合
  11. Collections.shuffle(list);
  12. System.out.println(list);
  13. //排序 默认自然判断
  14. Collections.sort(list);
  15. System.out.println(list);
  16. //降序
  17. Collections.sort(list, new Comparator<Integer>() {
  18. @Override
  19. public int compare(Integer o1, Integer o2) {
  20. return o2-o1;
  21. }
  22. });
  23. System.out.println(list);
  24. //找最大值
  25. List<Student> stuList = new ArrayList();
  26. stuList.add(new Student("李四",21,80));
  27. stuList.add(new Student("张三",20,85));
  28. stuList.add(new Student("李是是",18,90));
  29. stuList.add(new Student("王五",22,75));
  30. //找年龄最大的学生
  31. Student maxAgeStu = Collections.max(stuList, new Comparator<Student>() {
  32. @Override
  33. public int compare(Student o1, Student o2) {
  34. return o1.getAge() - o2.getAge();
  35. }
  36. });
  37. System.out.println(maxAgeStu);
  38. //找成绩最低的学生 min()
  39. //根据成绩降序排序
  40. //变成空集合
  41. List list1 = Collections.emptyList();
  42. System.out.println(list1);

发表评论

表情:
评论列表 (有 0 条评论,106人围观)

还没有评论,来说两句吧...

相关阅读