1. 程式人生 > >【Java】Treeset實現自定義排序

【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