【Java】Treeset实现自定义排序
2013-11-18 13:04
399 查看
两个类,一个学生类,含姓名和出生日期两个属性;还有一个学生排序类,重写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
相关文章推荐
- JAVA之旅(二十)—HashSet,自定义存储对象,TreeSet,二叉树,实现Comparator方式排序,TreeSet小练习
- JAVA之旅(二十)—HashSet,自定义存储对象,TreeSet,二叉树,实现Comparator方式排序,TreeSet小练习
- 【Java】Treeset实现自定义排序
- JAVA 中Comparator接口实现自定义排序的理解
- Java实现自定义对象的排序
- Java实现自定义对象的排序
- 在TreeSet中实现存储自定义对象,并且能够按照特定的顺序排序
- java 第八篇 使用comparator实现自定义排序
- java Collections.sort()实现List排序的默认方法和自定义方法
- Java 往TreeSet集合中存储自定义对象学生,按照学生的年龄进行排序。
- Java Collections.sort()实现List排序的默认方法和自定义方法
- TreeSet集合存放自定义类型的对象,可以使用比较器,实现Comparable接口自己设置排序方式
- 自定义多列排序:C++/Java实现
- java Collections.sort()实现List排序自定义方法
- java中利用Comparator接口实现自定义排序技巧。
- 使用Java中Comparator接口实现自定义排序
- solr入门之edismax权重排序使用之Java代码实现自定义权重
- JAVA compareTo实现treeSet()排序
- java 两种方式实现自定义排序
- Java针对ArrayList自定义排序的2种实现方法