关于Map迭代循环,key和value的顺序问题

使用Hashtable,keySet()返回的顺序为降序(key降顺序) ---->6, 5, 4, 3, 2, 1
使用TreeMap,keySet()返回的顺序为升序(key升顺序) ---->1, 2, 3, 4, 5, 6
使用HashMap,keySet()返回的顺序为乱序(随机顺序) ---->3, 2, 1, 6, 5, 4
使用LinkedHashMap,keySet()返回的顺序为原序(put顺序) ---->1, 2, 6, 3, 4, 5

 1 package map2json;
 2 
 3 import java.util.HashMap;
 4 import java.util.Hashtable;
 5 import java.util.Iterator;
 6 import java.util.LinkedHashMap;
 7 import java.util.Map;
 8 import java.util.Map.Entry;
 9 import java.util.Set;
10 import java.util.TreeMap;
11 
12 public class IterMap {
13     public static void main(String[] args) {
14         map1();
15         map2();
16         map3();
17         getKV();
18     }
19 
20     public static Map<String, String> setMap() {
21         // 使用Hashtable,keySet()返回的顺序为降序(key降顺序) ---->6, 5, 4, 3, 2, 1
22         // 使用TreeMap,keySet()返回的顺序为升序(key升顺序) ---->1, 2, 3, 4, 5, 6
23         // 使用HashMap,keySet()返回的顺序为乱序(随机顺序) ---->3, 2, 1, 6, 5, 4
24         // 使用LinkedHashMap,keySet()返回的顺序为原序(put顺序) ---->1, 2, 6, 3, 4, 5
25         Map<String, String> map = new LinkedHashMap<String, String>();
26         map.put("1", "a");
27         map.put("2", "b");
28         map.put("6", "a");
29         map.put("3", "c");
30         map.put("4", "d");
31         map.put("5", "e");
32         return map;
33     }
34 
35     public static void map1() {
36 
37         Set<String> set = setMap().keySet();
38         System.out.println(set.toString());
39         for (String str : set) {
40             String valueString = setMap().get(str);
41             System.out.println(str + ":" + valueString);
42         }
43     }
44 
45     // 通过实体getKey和getValue
46     public static void map2() {
47         Iterator<Entry<String, String>> it = setMap().entrySet().iterator();
48         while (it.hasNext()) {
49             Entry<String, String> entry = it.next();
50             System.out.println("key= " + entry.getKey() + " and value= "
51                     + entry.getValue());
52         }
53     }
54 
55     // 数据较多时使用
56     public static void map3() {
57         for (Entry<String, String> en : setMap().entrySet()) {
58             en.getKey();
59             en.getValue();
60             System.out.println(en.getKey() + ":" + en.getValue());
61         }
62     }
63 
64     // 得到所有的key和value的方法
65     public static void getKV() {
66         System.out.println(setMap().keySet().toString());
67         System.out.println(setMap().values().toString());
68     }
69 
70 }

猜你喜欢

转载自www.cnblogs.com/hyblogs/p/10451641.html