使用TreeSet集合存储元素,使用Comparable和Comparator比较元素

  • 使用Comparable接口对下列四位同学的 成绩降序 排序,如果成绩一样,那在成绩排序的基础上按照 年龄 排序。
package com.csdn.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Collections;
import java.util.TreeSet;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Comparable {
    private String name;
    private int age;
    private double score;

    @Override
    public int compareTo(Student stu) {
        if (this.getScore() > stu.getScore()) {
            return -1;
        } else if (this.getScore() < stu.getScore()) {
            return 1;
        }
        return this.getAge() - stu.getAge();
    }

    public static void main(String[] args) {
        System.out.println("按照成绩和年龄排序:");
        TreeSet set = new TreeSet<>();
        Collections.addAll(set, new Student("d", 20, 90.0),
                new Student("c", 22, 90.0),
                new Student("b", 20, 99.0),
                new Student("a",22,100.0));

        //自动调用Student中compareTo()方法

        for (Student student : set) {
            System.out.println(student);
        }
/*
       [Student(name=a,age=22, score=100.0),
       Student(name=b, age=20, score=99.0),
       Student(name=d, age=20, score=90.0),
       Student(name=c, age=22, score=90.0)]
*/

    }
}
  • 使用Comparator实现按照 姓名 排序

你可能感兴趣的:(#,集合,java,开发语言)