TreeSet 的用法

TreeSet 实现了 SortedSet 接口,可以对集合中的元素进行排序,前提要求集合中的元素必须可比较大小。

Set集合 - 鹿先森JIAN - 博客园 (cnblogs.com)Collection集合 - 鹿先森JIAN - 博客园 (cnblogs.com)

设置方法有两种:

  (1)比较器排序:在构造方法中指定 Comparator比较器。

  (2)自然排序:如果没有在构造方法中指定 Comparator,则要求 元素的类(eg:Student类) 实现 Comparable接口,并重写 compareTo(Object o)方法。

如果以上两种方法都设置了,则系统会选择 比较器排序,因为它优先于 自然排序。

 案例一:采用自然排序方法

package cn.powernode.javase.student_sort;
/*
    1.该类实现一个 Comparable接口,该接口可以提供排序的方法
    2.重写 Comparable接口中的排序方法 compareTo()方法,该方法中提供排序规则
 */
public class Student implements Comparable<Student>{
    private String sNum;        // 学号
    private String name;        // 姓名
    private int chineseScore;   // 语文成绩
    private int mathScore;      // 数学成绩
    // Alt+Insert, 提供所有 Getter and Setter 方法
    public String getsNum() {    return sNum;    }
    public void setsNum(String sNum) {    this.sNum = sNum;    }
    public String getName() {    return name;    }
    public void setName(String name) {    this.name = name;    }
    public int getChineseScore() {    return chineseScore;    }
    public void setChineseScore(int chineseScore) {    this.chineseScore = chineseScore;    }
    public int getMathScore() {    return mathScore;    }
    public void setMathScore(int mathScore) {    this.mathScore = mathScore;    }
    // 提供 有参构造 和 无参构造
    public Student() {    }
    public Student(String sNum, String name, int chineseScore, int mathScore) {
        this.sNum = sNum;
        this.name = name;
        this.chineseScore = chineseScore;
        this.mathScore = mathScore;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sNum='" + sNum + '\'' +
                ", name='" + name + '\'' +
                ", chineseScore=" + chineseScore +
                ", mathScore=" + mathScore +
                ", sumScore=" + getSumScore() +
                '}';
    }
    // 获取总成绩
    public int getSumScore(){
        return chineseScore + mathScore;
    }
    /*
    比较条件有 主要条件 和 次要条件
    题目只会给你描述主要条件,按照主要条件进行排序,不会描述次要条件;
    但是你需要自己分析次要条件是什么,什么时候排?
    主要条件:总分                 总分相同,则继续比较次要条件
    次要条件1:语文成绩             总分相同,再比较语文成绩
    次要条件2:姓名的字典表顺序      语文成绩也相同,再比较姓名
    次要条件3:学号                姓名也相同,再比较学号
    */
    @Override
    public int compareTo(Student o) {
        // result1 = 比较总分
        int result1 = o.getSumScore() - this.getSumScore();
        // result2 = (比较总分==0 ? 比较语文成绩 : 比较总分)
        int result2 = result1 == 0 ? o.getChineseScore() - this.getChineseScore() : result1;
        // result3 = (result2==0 ? 比较姓名 : result2)
        int result3 = result2 == 0 ? this.getName().compareTo(o.getName()) : result2;
        // result4 = (result3==0 ? 比较学号 : result3)
        int result4 = result3 == 0 ? this.getsNum().compareTo(o.getsNum()) : result3;
        return result4;
    }
    /* compareTo(Object o) 方法的返回结果,是用于控制集合中元素是否存在,以及存放顺序的
    返回   0:舍弃元素
    返回 正数:存入的元素放置在后面
    返回 负数:存入的元素放置在前面
    */
}
package cn.powernode.javase.student_sort;
import java.util.TreeSet;
/*
- 用 TreeSet集合存储多个学生信息(学号,姓名,语文成绩,数学成绩),要求按照总分从高到低进行排序
1.Student类,四个成员变量,描述四项信息
2.创建若干学生对象,给指定的值
3.选择一种排序方式,指定排序规则
4.将对象存入到 TreeSet集合中,看到集合中具备了排序效果
 */
public class Test01 {
    public static void main(String[] args) {
        Student s1 = new Student("s001", "zs", 70, 85);
        Student s2 = new Student("s002", "ls", 85, 70);
        Student s3 = new Student("s003", "ww", 85, 75);
        Student s4 = new Student("s004", "zl", 85, 75);
        Student s5 = new Student("s005", "zl", 85, 75);
        Student s6 = new Student("s005", "zl", 85, 75);

        TreeSet<Student> treeSet = new TreeSet<>();
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);
        treeSet.add(s5);
        treeSet.add(s6);

        for (Student student : treeSet) {
            System.out.println(student);
        }
    }
}
执行结果:
Student{sNum='s003', name='ww', chineseScore=85, mathScore=75, sumScore=160}
Student{sNum='s004', name='zl', chineseScore=85, mathScore=75, sumScore=160}
Student{sNum='s005', name='zl', chineseScore=85, mathScore=75, sumScore=160}
Student{sNum='s002', name='ls', chineseScore=85, mathScore=70, sumScore=155}
Student{sNum='s001', name='zs', chineseScore=70, mathScore=85, sumScore=155}

案例二:采用比较器排序方法

package cn.powernode.javase.treeset;
public class Student {
    private String name;    // 姓名
    private int age;        // 年龄
    private int score;      // 分数
    // Alt+Insert, 提供所有 Getter and Setter 方法
    public int getScore() {    return score;    }
    public void setScore(int score) {    this.score = score;    }
    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 Student() { }
    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
package cn.powernode.javase.treeset;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetTest02 {
    public static void main(String[] args) {
        Student s1= new Student("zs",12,99);
        Student s2= new Student("ls",15,97);
        Student s3= new Student("ww",11,95);
        Student s4= new Student("xh",10,98);
/*
        // 1.创建 Comparator比较器
        Comparator<Student> cc = new Comparator<>(){
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getScore()-o1.getScore(); // 比较分数
            }
        };
        // 2.在构造方法中指定 Comparator比较器
        TreeSet<Student> treeSet = new TreeSet<>(cc);
*/
    // 上面 1、2步也可以合在一起写,如下:
    TreeSet<Student> treeSet = new TreeSet<>( new Comparator<>(){
        @Override
        public int compare(Student o1, Student o2) {
            return o2.getScore()-o1.getScore(); // 比较哪个就写哪个
        }
    });
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);
        // foreach 遍历
        for (Student student : treeSet) {
            System.out.println(student);
        }
    }
}
执行结果:(根据 score 进行排序)
    Student{name='zs', age=12, score=99}
    Student{name='xh', age=10, score=98}
    Student{name='ls', age=15, score=97}
    Student{name='ww', age=11, score=95}

 

posted @ 2022-04-30 22:17  鹿先森JIAN  阅读(171)  评论(0编辑  收藏  举报