HashMap输出时是无序的
想要顺序输出就要借助其他map
HashMap缺点:HashMap是非线程安全的,多个线程同时写入可能导致数据不一致。解决办法详见:HashMap是非线程安全的解决办法
linkedHashMap:保持输入和输出顺序一致
LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("1","q");
linkedHashMap.put("5","q");
linkedHashMap.put("2","");
linkedHashMap.put("","");
linkedHashMap.put("","3");
// hashtable.put("4",null);
// hashtable.put(null,"6");
// hashtable.put(null,null);
linkedHashMap.forEach((key, value) -> {
System.out.println("Key-->" + key + " Value-->" + hashtable.get(key));
});
输出结果:
可以看出输出顺序和输入顺序完全相同,其中key为空的值,被后者覆盖掉了。
注意:LinkedHashMap允许key和value为空字符串,但不允许任意一个为null,否则报空指针异常;
TreeMap:按照key的升序排序,也可以利用比较器倒序排列
TreeMap<String,String> treeMap = new TreeMap<>();
treeMap.put("1","q");
treeMap.put("5","q");
treeMap.put("2","");
treeMap.put("","");
treeMap.put("","3");
// hashtable.put("4",null);
// hashtable.put(null,"6");
// hashtable.put(null,null);
treeMap.forEach((key, value) -> {
System.out.println("Key-->" + key + " Value-->" + hashtable.get(key));
});
输出结果:
可以看出TreeMap输出结果是按照key的升序进行排列的;
注意:TreeMap允许key和value为空字符串,但不允许任意一个为null,否则报空指针异常;
参考链接: Map遍历元素按put顺序输出