Comparator接口的使用:
TreeSet集合存储自定义类型的对象时,必须指定排序规则,支持如下两种方式来指定比较规则。
方式一
让自定义的类实现Comparable接口,重写里面的compareTo方法来指定比较规则。
//属性类
public class Student implements Comparable<Student>{
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public int compareTo(Student o) {
int num=this.age-o.age;
int num1=num==0?this.name.compareTo(o.name):num;
return num1;
}
}
import java.util.TreeSet;
public class TreeSetDemo1 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>();
Student stu1 = new Student("张三",18);
Student stu2 = new Student("李四",16);
Student stu3 = new Student("王五",19);
Student stu4 = new Student("赵二",21);
Student stu5 = new Student("孙达",16);
Student stu6 = new Student("赵二",21);
ts.add(stu2);
ts.add(stu3);
ts.add(stu4);
ts.add(stu5);
ts.add(stu6);
//遍历
for(Student s:ts){
System.out.println(s.getName()+" ,"+s.getAge());
}
}
}
方式二
通过调用TreeSet集合有参数构造器,可以设置Comparator对象(比较器对象,用于指定比较规则)
//属性类
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<>(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 stu1 = new Student("张三",18);
Student stu2 = new Student("李四",16);
Student stu3 = new Student("王五",19);
Student stu4 = new Student("赵二",21);
Student stu5 = new Student("孙达",16);
Student stu6 = new Student("赵二",21);
ts.add(stu1);
ts.add(stu2);
ts.add(stu3);
ts.add(stu4);
ts.add(stu5);
ts.add(stu6);
//遍历
for(Student s:ts){
System.out.println(s.getName()+" ,"+s.getAge());
}
}
}
标签:name,自定义,age,ts,Student,规则,new,排序,public
From: https://blog.csdn.net/2401_85045690/article/details/141967973