集合-TreeSet-Comparator

时间:2021-06-15 09:19:20
 package com.bjpowernode.tree2;

 public class Student {

     private String name;
private int 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) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
} }
 package com.bjpowernode.tree2;

 import java.util.Comparator;

 public class StudentComparator implements Comparator<Student> {

     @Override
public int compare(Student stu1, Student stu2) { if (stu1.getAge()==stu2.getAge()) {
return stu1.getName().compareTo(stu2.getName());
}
return stu1.getAge()-stu2.getAge();
} }
 package com.bjpowernode.tree2;

 import java.util.Set;
import java.util.TreeSet; public class TreeSet1 { public static void main(String[] args) { StudentComparator studentComparator=new StudentComparator();
Set<Student> set=new TreeSet<>(studentComparator);
Student stu1=new Student("张三", 66);
Student stu2=new Student("lisi", 23);
Student stu3=new Student("刘能", 45);
Student stu4=new Student("赵本山", 62);
Student stu5=new Student("赵本山", 62);
Student stu6=new Student("abc", 45);
set.add(stu1);
set.add(stu2);
set.add(stu3);
set.add(stu4);
set.add(stu5);
set.add(stu6);
// for (Student student : set) {
// System.out.println(student);
// }
System.out.println("姓名\t年龄");
// System.out.println("姓名"+"\t"+"年龄");
for (Student student : set) {
System.out.println(student.getName()+"\t"+student.getAge());
}
} }