天天看點

Java學習Set之比較器排序Comparator的使用

存儲學生對象并周遊,建立TreeSet集合使用帶參構造方法

要求:按照年齡從小大到排序,年齡相同時,按照姓名的字母順序排序

結論:

     1.用TreeSet集合存儲自定義對象,帶參構造方法使用的是比較器排序對元素進行排序 

package com.itheima_90;

import java.util.Comparator;
import java.util.TreeSet;
/*
   存儲學生對象并周遊,建立TreeSet集合使用帶參構造方法
   要求:按照年齡從小大到排序,年齡相同時,按照姓名的字母順序排序
 */

public class TreeSetDemo {
    public static void main(String[] args) {
        //建立集合對象
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //this.age - s.age
                //s1,s2
                int num = s1.getAge() - s2.getAge();
                int num2 = num ==0?s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });
        //建立學生對象
        Student s1 = new Student("java",33);
        Student s2 = new Student("hello",44);
        Student s3 = new Student("world",55);
        //添加元素
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        //周遊
        for(Student s:ts){
            System.out.println(s.getName() + ":" + s.getAge());
        }
        
    }

}      
package com.itheima_90;

public class Student {
    private String name;
    private int age;
    public Student(){}

    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;
    }
}