gogoWebsite

【Java】Treeset implements custom sorting

Updated to 20 days ago

Two classes, one student class, including two attributes: name and date of birth; there is also a student sorting class, rewrite the compare function, and the custom sorting rules are to compare the date of birth first, and if the same is the same, then compare the name and mother.

package birthday;

import ;

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) {
		 = name;
	}
	public Calendar getBirthday() {
		return birthday;
	}
	public void setBirthday(Calendar birthday) {
		 = birthday;
	}
	
}

package birthday;

 import ;
 import ;
 import ;
 import ;
 import ;

 public class ComparatorStudent implements Comparator<Student>{

	 @Override
	 public int compare(Student o1, Student o2) {
		 // TODO Auto-generated method stub
		 if (().equals(()))
			 {
				 if (().compareTo(())>0) return 1;
				 else if (().compareTo(())<0) return -1;
				 else return 0;
			 }
		 else if (().after(()))
			 return 1;
		 else
			 return -1;
	 }
	 public static void main(String ars[])
	 {
		 Set<Student> treeset = new TreeSet<Student>(new ComparatorStudent());
		 Calendar cal1 = ();
		 Calendar cal2 = ();
		 Calendar cal3 = ();
		 Calendar cal4 = ();
		 (1991,5,6);
		 (1992,2,5);
		 (1992,10,12);
		 (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);
		
		 (stu4);
		 (stu3);
		 (stu2);
		 (stu1);
		
		 SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		 for (Student s:treeset)
		 {
			 (()+" Date of birth: "+(().getTime()));
		 }
	 }
	
 }

Output result:

Mike Date of Birth: 1991-06-06
 Jack Date of Birth: 1992-03-05
 Lily Date of Birth: 1992-03-05
 Lucy Date of Birth: 1992-11-12