【Java學習筆記】Collections集合

阮巍發表於2021-01-03

Collections概述和使用

概述

Collections類是針對集合操作的工具類,常用方法有:

  1. public static <T extends Comparable<Tsuper T>>void sort(List<Tlist>):將指定的List列表按生序排序
  2. public static void reverse(List<?>list): 反轉指定列表中元素的順序
  3. public static void shuffle(List<?>list):使用預設的隨機源隨機排列指定的列表
    public static void main(String[] args) {
        ArrayList<Integer>list=new ArrayList<>();
        list.add(10);
        list.add(30);
        list.add(20);
        list.add(80);
        list.add(5);
        list.add(40);

        System.out.println(list);

        //1. sort升序
        Collections.sort(list);
        System.out.println(list);

        //2.reverse反轉
        Collections.reverse(list);
        System.out.println(list);

        //3.shuffle隨機置換
        Collections.shuffle(list);
        System.out.println(list);


    }

列印結果如下:

[10, 30, 20, 80, 5, 40]
[5, 10, 20, 30, 40, 80]
[80, 40, 30, 20, 10, 5]
[5, 80, 30, 20, 40, 10]

Process finished with exit code 0

使用

案例:ArrayList儲存學生物件並排序,要求:按照年齡從小到大排序,年齡相同時,按照姓名和字母順序排序

//1.定義學生類
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

    public static void main(String[] args) {
        //2.建立ArrayList集合物件
        ArrayList<Student>list=new ArrayList<>();

        //3.建立學生物件
        Student student1=new Student("A",25);
        Student student2=new Student("H",18);
        Student student3=new Student("I",23);
        Student student4=new Student("G",20);
        Student student5=new Student("B",20);


        //4.把學生物件新增到集合
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);


        //5.使用Collections對ArrayList集合排序
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //按照年齡從小到大排序,年齡相同時,按照姓名的字母順序排序
                int num1=s1.getAge()-s2.getAge();
                int num2=num1==0?s1.getName().compareTo(s2.getName()):num1;
                return num2;
            }
        });


        //6.遍歷集合
        for(Student student:list){
            System.out.println(student.getName()+","+student.getAge());
        }

    }

列印結果如下:


H,18
B,20
G,20
I,23
A,25

Process finished with exit code 0

相關文章