【发布时间】:2019-02-16 16:58:13
【问题描述】:
我正在尝试使用LinkedHashMap和TreeMap对HashMap的输出进行排序。
当我使用TreeMap 来整理HashMap 时,它就像一个魅力。
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(40, "d");
hMap.put(10, "a");
hMap.put(30, "c");
hMap.put(20, "b");
System.out.println(" ");
System.out.println("before");
for (Map.Entry m1 : hMap.entrySet()) {
System.out.print(m1.getKey() + " " + m1.getValue() + " ");
}
System.out.println("after");
Map<Integer, String> hTree = new TreeMap<Integer, String>(hMap);
for (Map.Entry m2 : hTree.entrySet()) {
System.out.print(m2.getKey() + " " + m2.getValue() + " ");
}
输出:before
20 b 40 d 10 a 30 c
after
10 a 20 b 30 c 40 d
但是当我尝试使用LinkedHashMap 对HashMap 进行排序时,它似乎不起作用。
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(10, "a");
hMap.put(20, "b");
hMap.put(30, "c");
hMap.put(40, "d");
System.out.println("before");
for (Map.Entry m1 : hMap.entrySet()) {
System.out.print(m1.getKey() + " " + m1.getValue() + " ");
}
System.out.println(" ");
System.out.println("after");
LinkedHashMap<Integer, String> lhMap = new LinkedHashMap<Integer, String>(hMap);
Iterator it = lhMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry me = (Map.Entry) it.next();
System.out.print(me.getKey() + " " + me.getValue()+" ");
}
输出:
before
20 b 40 d 10 a 30 c
after
20 b 40 d 10 a 30 c
谁能告诉我为什么这种排序不起作用?那是因为LinkedHashMap 正在过滤HashMap?
如果这是为什么TreeMap 对这个问题免疫?
谢谢
【问题讨论】:
-
是什么让您觉得
LinkedHashMap可以排序任何东西? -
@SotiriosDelimanolis 它按插入顺序排序。
-
你得到了插入顺序作为输出。
-
@LuCio。不它不是。广告订单是
10,20,30,40。输出为20,40,10,30。请看第二个例子 -
@pippilongstocking 这是 HashMap 的插入顺序。不是 LinkedHashMap 的插入顺序。您将 HashMap 传递给 LinkedHashMap 构造函数。因此,此构造函数遍历 HashMap(没有排序),并将 HashMap 的每个元素插入到 LinkedHashMap 中。如您所见,您得到的顺序与 HashMap 中的顺序相同,这表明保留了插入顺序。
标签: java collections hashmap treemap linkedhashmap