码迷,mamicode.com
首页 > 编程语言 > 详细

TreeMap的排序功能,构造方法

时间:2016-05-06 00:15:44      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

/**
 *    /*
         * 练习二:
         * 学生对象(姓名,年龄)都有自己的归属地,既然有对应关系。
         * 将学生对象和归属地存储到map集合中。
         * 注意:同姓名同年龄视为重复的键。

                      按照学生的年龄进行从小到大的排序。 
         * 如果要对学生按照姓名排序呢?
       
 */
public class Practise2 {

    public static void main(String[] args) {
        /*创建Map集合*/
        Map<Student,String> classMap = new HashMap<Student,String>();
        classMap.put(new Student("小明",15), "上海");
        classMap.put(new Student("小李",15), "沈阳");
        classMap.put(new Student("小徐",13), "武汉");
        classMap.put(new Student("小明",15), "上海");        //视为重复的键
        classMap.put(new Student("天天",14), "武汉");
        classMap.put(new Student("刚刚",12), "河北");
        
        /*排序,想到treeSet,比较简单,按姓名排序,按年龄为自然排序*/
        Map<Student,String> classTreeMap = new TreeMap<Student,String>(new Comparator<Student>() {

            @Override
            public int compare(Student o1, Student o2) {
                int temp = o1.getName().compareTo(o2.getName());
                return temp==0?o1.compareTo(o2):temp;
            }
        });
        classTreeMap.put(new Student("小明",15), "上海");
        classTreeMap.put(new Student("小李",15), "沈阳");    
        classTreeMap.put(new Student("小徐",13), "武汉");
        classTreeMap.put(new Student("小明",15), "上海");        //视为重复的键
        classTreeMap.put(new Student("天天",14), "武汉");
        classTreeMap.put(new Student("刚刚",12), "河北");

        for(Student stu : classTreeMap.keySet()){
            System.out.println(stu);
        }
        
        /*Map转成List的办法*/
        List<Map.Entry<Student, String>> list = new ArrayList<Map.Entry<Student, String>>(classTreeMap.entrySet());

        for(Entry ent: list){
            System.out.println(ent.getKey());
            System.out.println(ent.getValue());
        }
    }
}

 

TreeMap的排序功能,构造方法

标签:

原文地址:http://www.cnblogs.com/zyjcxc/p/5463632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!