【Collections:集合工具類:天然排序和比較器排序】

package com.yjf.esupplier.common.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author shusheng
 * @description 天然排序和比較器排序(對象)
 * @Email shusheng@yiji.com
 * @date 2018/12/18 17:11
 */
public class CollectionsDemo1 {

    public static void main(String[] args) {
        // 建立集合對象
        List<Student> list = new ArrayList<Student>();

        // 建立學生對象
        Student s1 = new Student("林青霞", 27);
        Student s2 = new Student("風清揚", 30);
        Student s3 = new Student("劉曉曲", 28);
        Student s4 = new Student("武鑫", 29);
        Student s5 = new Student("林青霞", 27);

        // 添加元素對象
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);
        list.add(s5);

        // 排序
        // 天然排序(須比較對象實現Comparable接口)
        Collections.sort(list);
        // 遍歷集合
        for (Student s : list) {
            System.out.println(s.getName() + "---" + s.getAge());
        }
        System.out.println("---------------------------------------");
        // 比較器排序
        // 若是同時有天然排序和比較器排序,以比較器排序爲主
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s2.getAge() - s1.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName())
                        : num;
                return num2;
            }
        });

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

    }

}

class Student implements Comparable<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;
    }

    @Override
    public int compareTo(Student s) {
        int num = this.age - s.age;
        int num2 = num == 0 ? this.name.compareTo(s.name)
                : num;
        return num2;
    }
}
相關文章
相關標籤/搜索