本文转自:http://liudeh-009.iteye.com/blog/1847626
在项目开发中,经常回用到容器排序,而它们的写法比较固定,今天就来总结一下.
pojo类如下:
Java代码 - package com.ldh;
-
- public class Student implements Comparable<Student> {
- private int id;
- private String name;
- private int age;
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- @Override
- public int compareTo(Student o) {
- return new Integer(age).compareTo(new Integer(o.getAge()));
- }
- }
再创建四个Student对象:
Java代码 - Student st1 = new Student();
- st1.setName("zhangsan1");
- st1.setId(1);
- st1.setAge(30);
-
- Student st2 = new Student();
- st2.setName("zhangsan2");
- st2.setId(2);
- st2.setAge(20);
-
- Student st3 = new Student();
- st3.setName("zhangsan3");
- st3.setId(3);
- st3.setAge(10);
-
- Student st4 = new Student();
- st4.setName("zhangsan4");
- st4.setId(4);
- st4.setAge(10);
用TreeSet对上述四个Student对象排序并打印出结果:Java代码 - Set<Student> set = new TreeSet<Student>();
- set.add(st1);
- set.add(st2);
- set.add(st3);
- set.add(st4);
-
- for(Student st : set){
- System.out.println(st.getAge());
- }
- System.out.println(set.size());
打印出的结果如下:
10
20
30
3
TreeSet底层排序算法是二叉树,如果两个元素比较的结果为0,就被视为同一个元素.如果 Student没有实现Comparable接口,也可以通过以下方式实现排序:
Java代码 - Set<Student> set = new TreeSet<Student>(new Comparator<Student>() {
- @Override
- public int compare(Student o1, Student o2) {
- return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()) );
- }
- });
最终打印出的结果和实现Comparable接口一样.TreeSet的底层实现结构是TreeMap,TreeSet就是value都相同的TreeMap,因此TreeMap也有上述两种排序方式.