重写compare的方法,来实现
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 int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
import java.util.Comparator;
import java.util.TreeSet;
public class Testdemo {
public static void main(String[] args) {
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("xishi",29);
Student s2 = new Student("diaocahn",20);
Student s3 = new Student("wangzhaojun",29);
Student s4 = new Student("yangyuhuan",25);
Student s5 = new Student("lubu",26);
Student s6 = new Student("xaioyao",19);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
for(Student i:ts){
System.out.println(i.getName() + " " + i.getAge());
}
}
}
输出:
xaioyao 19
diaocahn 20
yangyuhuan 25
lubu 26
wangzhaojun 29
xishi 29