【Java】Treeset实现自定义排序

这篇博客探讨了如何通过创建自定义的Comparator类来实现Java TreeSet的按出生日期和姓名排序。首先定义了一个学生类,包含姓名和出生日期属性,然后创建了一个学生排序类,重写compare方法,以出生日期为主排序依据,当日期相同时,根据姓名的字母顺序进行次级排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两个类,一个学生类,含姓名和出生日期两个属性;还有一个学生排序类,重写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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值