TreeSet的比较器排序Comparator的使用

package com.czie.iot1913.lps.itheima02;

import java.util.Comparator;
import java.util.TreeSet;

/**
* @author 1944900433@qq.com
* @date 2022-03-18 22:21
*/
public class TreeSetDemo01 {
public static void main(String[] args) {
//TreeSet(Collection<? extends E> c)
//构造一个新的树集包含在指定集合的元素,根据其元素的自然排序排序。

TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num=s1.getAge()-s2.getAge();
int num2=num==0? s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
Student s1 = new Student("西施",21);
Student s2 = new Student("杨玉环",22);
Student s3 = new Student("貂蝉",20);
Student s4 = new Student("王昭君",19);
Student s5 = new Student("昭君",19);
Student s6 = new Student("昭君",19);

ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);

for (Student s:ts){
System.out.println(s.getName()+","+ s.getAge());
}

}
}




package com.czie.iot1913.lps.itheima02;

import java.util.Objects;

/**
* @author 1944900433@qq.com
* @date 2022-03-18 22:20
*/
public class Student {
private String name;
private int age;

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}

@Override
public int hashCode() {
return Objects.hash(name, 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 Student(String name, int age) {
this.name = name;
this.age = age;
}

public Student() {
}
}
posted @ 2022-03-18 22:53  刘品水  阅读(61)  评论(0)    收藏  举报