1 package com.jdk7.chapter4;
2
3 import java.util.Comparator;
4 import java.util.HashMap;
5 import java.util.Iterator;
6 import java.util.Map;
7 import java.util.TreeMap;
8
9 /**
10 * 继承Comparator的compare方法,简化比较细节
11 * Map的几种类型中只有TreeMap是会排序的,默认为升序
12 * 如果要对Map其他类型进行排序,需要将其他类型Map作为TreeMap构建的参数,从而达到按'键'升序排列
13 * 如果希望按照自定义规则排序,首先自定义规则函数所在类需要实现接口Comparator的compare方法,然后需要将自定义排序规则所在类对象作为TreeMap构建的参数
14 * @author Administrator
15 *
16 */
17 public class MapSortTest implements Comparator {
18
19 /**
20 * 创建MapSortTest时会加载覆盖父类的compare方法,作为排序规则
21 */
22 @Override
23 public int compare(Object o1, Object o2) {
24 //将o1和o2转换为int类型
25 int num1 = ((Integer)o1).intValue();
26 int num2 = ((Integer)o2).intValue();
27 if(num1<num2){
28 return 1;
29 }else if(num1>num2){
30 return -1;
31 }
32 return 0;
33 }
34
35 public static void printMap(Map map){
36 Map.Entry entry = null;
37 Iterator it = map.entrySet().iterator();
38 while(it.hasNext()){
39 entry = (Map.Entry)it.next();
40 System.out.println("key: "+entry.getKey()+" value: "+entry.getValue());
41 }
42 System.out.println();
43 }
44
45 public static void main(String[] args) {
46 MapSortTest mt = new MapSortTest();
47 Map mapm = new HashMap();
48 mapm.put(001, "Hello");
49 mapm.put(004, "Lily");
50 mapm.put(003, "Rucy");
51 mapm.put(002, "Hanmei");
52 System.out.println("初始化后的Map>");
53 mt.printMap(mapm);
54 System.out.println("默认排序后的Map>");
55 Map mapt = new TreeMap(mapm);
56 mt.printMap(mapt);
57 System.out.println("自定义排序后的Map>");
58 //构建TreeMap对象时,参数为排序函数compare
59 // mapt = new TreeMap(new MapSortTest());
60 mapt = new TreeMap(mt);
61 mapt.putAll(mapm);
62 mt.printMap(mapt);
63 }
64 }
65
66 执行结果:
67 初始化后的Map>
68 key: 1 value: Hello
69 key: 2 value: Hanmei
70 key: 3 value: Rucy
71 key: 4 value: Lily
72
73 默认排序后的Map>
74 key: 1 value: Hello
75 key: 2 value: Hanmei
76 key: 3 value: Rucy
77 key: 4 value: Lily
78
79 自定义排序后的Map>
80 key: 4 value: Lily
81 key: 3 value: Rucy
82 key: 2 value: Hanmei
83 key: 1 value: Hello