Java_基础—TreeMap集合键是Student值是String的案例

Student类,属性为name,age
实现接口Comparable,重写comparTo()方法,通过年龄的大小进行排序实现

public class Student implements Comparable<Student>{
        @Override
        public int compareTo(Student o) {
            int num = this.age - o.age;
            return num == 0 ? this.name.compareTo(o.name) : num;
        }       

}

TreeMap类

package com.soar.map;

import java.util.Comparator;
import java.util.TreeMap;

import com.soar.bean.Student;

public class Demo7_TreeMap {
    /*
     * * A:案例演示
     * TreeMap集合键是Student值是String的案例
     */
    public static void main(String[] args) {
        //comparator();
        TreeMap<Student,String> tm = new TreeMap<>(new Comparator<Student>(){

            @Override
            public int compare(Student s1, Student s2) {
                int num = s1.getName().compareTo(s2.getName());     //按照姓名的Unicode码比较
                return num == 0 ? s1.getAge() - s2.getAge() : num;
            }   
        });

        tm.put(new Student("张三",23),"北京");
        tm.put(new Student("李四",24),"上海");
        tm.put(new Student("王五",25),"广州");
        tm.put(new Student("赵六",26),"深圳");

        System.out.println(tm);         //在Student对象类中重写comparTo方法,按照年龄的大小比较进行排序

    }

    private static void comparator() {
        TreeMap<Student,String> tm = new TreeMap<>();
        tm.put(new Student("张三",23),"北京");
        tm.put(new Student("李四",24),"上海");
        tm.put(new Student("王五",25),"广州");
        tm.put(new Student("赵六",26),"深圳");

        System.out.println(tm);
    }

}
posted @ 2017-07-18 15:39  Soar_Sir  阅读(244)  评论(0编辑  收藏  举报