【Java】Treeset实现自定义排序
两个类,一个学生类,含姓名和出生日期两个属性;还有一个学生排序类,重写compare函数,自定义排序规则是先比较出生日期,如果相同再比较姓名字母
package birthday; import java.util.Calendar; public class Student { private String name; private Calendar birthday; Student(String aname,Calendar date) { name=aname; birthday=date; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Calendar getBirthday() { return birthday; } public void setBirthday(Calendar birthday) { this.birthday = birthday; } }
package birthday; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class ComparatorStudent implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub if (o1.getBirthday().equals(o2.getBirthday())) { if (o1.getName().compareTo(o2.getName())>0) return 1; else if (o1.getName().compareTo(o2.getName())<0) return -1; else return 0; } else if (o1.getBirthday().after(o2.getBirthday())) return 1; else return -1; } public static void main(String ars[]) { Set<Student> treeset = new TreeSet<Student>(new ComparatorStudent()); Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); Calendar cal3 = Calendar.getInstance(); Calendar cal4 = Calendar.getInstance(); cal1.set(1991,5,6); cal2.set(1992,2,5); cal3.set(1992,10,12); cal4.set(1992,2,5); Student stu1 = new Student ("Mike",cal1); Student stu2 = new Student ("Jack",cal2); Student stu3 = new Student ("Lucy",cal3); Student stu4 = new Student ("Lily",cal4); treeset.add(stu4); treeset.add(stu3); treeset.add(stu2); treeset.add(stu1); SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); for (Student s:treeset) { System.out.println(s.getName()+" 出生日期: "+dateformat.format(s.getBirthday().getTime())); } } }
输出结果:
Mike 出生日期: 1991-06-06 Jack 出生日期: 1992-03-05 Lily 出生日期: 1992-03-05 Lucy 出生日期: 1992-11-12