zoukankan      html  css  js  c++  java
  • 黑马程序员JavaAPI16天7(TreeMap练习)

    package string.test;
    
    import java.util.Comparator;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeMap;
    
    /*
     * 
     * 需求:对学生对象的年龄经行升序排序
     * 
     * 因为数据是以键值对形式存在的。
     * 所以要使用可以排序的Map集合。TreeMap
     * 
     * 定义一个对Student的排序类StuNameComparator 要求安名称进行排序 如果名称相同就按年龄进行排序
     */
    class StuNameComparator implements Comparator<Student> {
    
        @Override
        public int compare(Student o1, Student o2) {
            int num = o1.getName().compareTo(o2.getName());
            if (num == 0) {
                return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
            }// TODO Auto-generated method stub
            return num;
        }
    }
    
    public class MapDemo5 {
        public static void main(String[] args) {
            Map<Student, String> map = new TreeMap<Student, String>(new StuNameComparator());
            map.put(new Student("zhangsan", 20), "beijing");
            map.put(new Student("lisi", 21), "tianjing");
            // map.put(new Student("lisi", 21),
            // "guangzhou");会把上面的的value替换掉(应为存入了相同的Key)
            map.put(new Student("wangwu", 22), "hunan");
            map.put(new Student("zhaoliu", 27), "hubei");
            map.put(new Student("zhaoliu", 23), "hubei");
            Set<Map.Entry<Student, String>> keyEntry = map.entrySet();
            Iterator<Map.Entry<Student, String>> me = keyEntry.iterator();
            while (me.hasNext()) {
                Map.Entry<Student, String> entry = me.next();
                System.out.println("姓名:" + entry.getKey().getName() + ",年龄:" + entry.getKey().getAge() + ",地址:" + entry.getValue());
            }
    
        }
    }
    /*
     * 以上案列用到了16-6中的学生类
     */
  • 相关阅读:
    TCP协议实现双工通信
    搭建本地FTP服务器
    CSS 3 选择器root、not、empty、target
    CSS 3 中的伪类选择器
    CSS 3 中的属性选择器
    Entity Framework Code First属性映射约定
    Entity Framework数据库初始化四种策略
    HTML 5 Base 64 编码
    HTML 5 离线程序
    HTML5 本地数据库IndexedDB数据库
  • 原文地址:https://www.cnblogs.com/guwenren/p/2970672.html
Copyright © 2011-2022 走看看