选择某种Map集合保存学号从1到15的学员的学号(键)和姓名(值),学号用字符串表示,输入的时候要以学号乱序的方式存入Map集合,然后按照学号从大到小的顺序将Map集合中的元素输出打印。需要自定义Map集合的比较器Comparator,因字符串对象的大小比较是按字典序,而非对应的数值。
要求:必须使用Map集合的内部排序机制进行排序,不能在外部排序。
(1)代码实现
- import java.util.*;
-
- public class MapTest {
-
- public static void main(String[] args) {
-
- TreeMap tm =new TreeMap(new MyComparator());
-
- tm.put("1006", "政焕");
- tm.put("1003", "子墨");
- tm.put("1002", "伯懿");
- tm.put("1004", "在凡");
- tm.put("1005", "炎彬");
- tm.put("1015", "瑾瑜");
- tm.put("1001", "恩畅");
- tm.put("1009", "真熙");
- tm.put("1010", "智熙");
- tm.put("1008", "胜恩");
- tm.put("1014", "幼林");
- tm.put("1011", "贞贤");
- tm.put("1007", "秀智");
- tm.put("1012", "孝琳");
- tm.put("1013", "敏智");
-
- Set keySet=tm.keySet();
-
- Iterator it=keySet.iterator();
- while(it.hasNext()) {
-
- Object key=it.next();
-
- Object value=tm.get(key);
-
- System.out.println(key +":"+value);
- }
-
-
-
-
-
-
- }
-
- }
-
- class MyComparator implements Comparator{
-
- public int compare(Object b1, Object b2) {
- String s1=(String)b1;
- String s2=(String)b2;
- return s2.compareTo(s1);
- }
-
- }
(2)运行结果
- 1015:瑾瑜
- 1014:幼林
- 1013:敏智
- 1012:孝琳
- 1011:贞贤
- 1010:智熙
- 1009:真熙
- 1008:胜恩
- 1007:秀智
- 1006:政焕
- 1005:炎彬
- 1004:在凡
- 1003:子墨
- 1002:伯懿
- 1001:恩畅