Java中TreeMap类

TreeMap

TreeMap实现SortedMap接口,能够把它保存的记录根据键排序,默认是按键值的升序排序,也可以指定排序的比较器,当用Iterator遍历TreeMap时,得到的记录是排过序的。如果使用排序的映射,建议使用TreeMap。在使用TreeMap时,key必须实现Comparable接口或者在构造TreeMap传入自定义的Comparator,否则会在运行时抛出java.lang.ClassCastException类型的异常。


之前总结TreeSet类中实现排序的源码,发现是由TreeMap类进行实现的,所以在TreeMap中key如果是自定义类则需要自己定义规则来进行排序,有两种办法

在Student类中实现Comparable,重写compareTo方法
在构造函数中new Comparator,匿名内部类,重写compare 方法

以下的代码将展示第二种排序方式

public class TestTreeMap {
    public static void main(String[] args) {
        //1.创建集合
        TreeMap<Student, String> map = new TreeMap<Student, String>(new Comparator<Student>() {
            //按照年龄来排序,年龄相同按照姓名来排序
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.getAge()==o2.getAge()){
                    return o1.getName().compareTo(o2.getName());
            }
            return o1.getAge()-o2.getAge();
            });
        //2.创建学生对象并往集合中增加
        Student s1 = new Student("张三",27);
        Student s2 = new Student("李四",29);
        Student s3 = new Student("王五",16);
        Student s4 = new Student("张三",27);
        map.put(s1, "2001");
        map.put(s2, "2002");
        map.put(s3, "2003");
        map.put(s4, "2004");

        //3.遍历集合 ,排序完成
        Set<Student> set = map.keySet();
        for(Student student : set){
            String value = map.get(student);
            System.out.println(student.getName()+"=="+student.getAge()+"=="+value);
        }
    }
}
附上TreeSet类的地址便于回顾: 点击打开链接

猜你喜欢

转载自blog.csdn.net/scbiaosdo/article/details/80329241