map

来源:互联网 发布:润网数据 编辑:程序博客网 时间:2024/06/06 07:31

选择某种Map集合保存学号从1到15的学员的学号(键)和姓名(值),学号用字符串表示,输入的时候要以学号乱序的方式存入Map集合,然后按照学号从大到小的顺序将Map集合中的元素输出打印。需要自定义Map集合的比较器Comparator,因字符串对象的大小比较是按字典序,而非对应的数值。

要求:必须使用Map集合的内部排序机制进行排序,不能在外部排序。

import java.util.Comparator;import java.util.Iterator;import java.util.TreeMap;public class mapTest {    public static void main(String[] args) {        // TODO Auto-generated method stub        TreeMap map=new TreeMap(new myComparator());        map.put("2", "依依");        map.put("1", "洋洋");        map.put("3", "啊啊");        map.put("4", "笨笨");        map.put("5", "试试");        map.put("6", "李三");        map.put("7", "李七");        map.put("8", "李八");        map.put("9", "李九");        map.put("10", "胡十");        map.put("11", "胡十一");        map.put("12", "王二");        map.put("13", "王三");        map.put("14", "张四");        map.put("15", "张五");        Iterator it=map.keySet().iterator();        while(it.hasNext()) {            Object key=it.next();            System.out.println(key+" : "+map.get(key));        }    }}class myComparator implements Comparator{    public int compare(Object o1, Object o2) {        // TODO Auto-generated method stub        return Integer.parseInt((String)o2)-Integer.parseInt((String)o1);    }}


原创粉丝点击