集合(三)集合的工具类Collections
Collections: 是集合的工具类
1.常用方法:
static <T> boolean addAll(Collection<? super T> c, T... elements)
//把数组的元素添加到集合
static void reverse(List<?> list) //把List集合的元素反转
static void shuffle(List<?> list) //随机打乱List集合元素的顺序
static <T extends Comparable<? super T>>
void sort(List<T> list) //自然排序
static <T> void sort(List<T> list, Comparator<? super T> c) //指定排序
2.应用(例子)
Integer[] arr = new Integer[]{1,3,5,4,2,1};
//把数组的元素添加到集合中
List<Integer> list = new ArrayList<>();
//Collections.addAll()
Collections.addAll(list,arr);
System.out.println(list);
//反转
Collections.reverse(list);
System.out.println(list);
//随机打乱集合
Collections.shuffle(list);
System.out.println(list);
//排序 默认自然判断
Collections.sort(list);
System.out.println(list);
//降序
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
System.out.println(list);
//找最大值
List<Student> stuList = new ArrayList();
stuList.add(new Student("李四",21,80));
stuList.add(new Student("张三",20,85));
stuList.add(new Student("李是是",18,90));
stuList.add(new Student("王五",22,75));
//找年龄最大的学生
Student maxAgeStu = Collections.max(stuList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
});
System.out.println(maxAgeStu);
//找成绩最低的学生 min()
//根据成绩降序排序
//变成空集合
List list1 = Collections.emptyList();
System.out.println(list1);
还没有评论,来说两句吧...