1、HashMap遍历是无序的,而Linkedhashmap和TreeMap遍历是有序的。
2、请看遍历事例代码:
private static void sortHashMap() {结果:
long startTime = System.currentTimeMillis();
Map<String, String> map = new HashMap<>();
map.put("jhj", "Jan");
map.put("gfg", "Ray");
map.put("qw", "Cole");
map.put("gfgf", "Emmy");
map.put("ty", "Mary");
map.put("er", "Eli");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
System.out.println("HashMap遍历花费的时间Time=" + (System.currentTimeMillis() - startTime));
System.out.println("=================");
}
private static void sortLinkedHashMap() {
long startTime = System.currentTimeMillis();
Map<String, String> map = new LinkedHashMap<>();
map.put("jhj", "Jan");
map.put("gfg", "Ray");
map.put("qw", "Cole");
map.put("gfgf", "Emmy");
map.put("ty", "Mary");
map.put("er", "Eli");
for (String name : map.keySet()) {
System.out.println(name + "-->" + map.get(name));
}
System.out.println("LinkedHashMap遍历花费的时间Time=" + (System.currentTimeMillis() - startTime));
System.out.println("=============");
}
private static void sortTreeMap() {
long startTime = System.currentTimeMillis();
Map<String, String> map = new TreeMap<>();
map.put("jhj", "Jan");
map.put("gfg", "Ray");
map.put("qw", "Cole");
map.put("gfgf", "Emmy");
map.put("ty", "Mary");
map.put("er", "Eli");
for (String name : map.keySet()) {
System.out.println(name + "-->" + map.get(name));
}
System.out.println("TreeMap遍历花费的时间Time=" + (System.currentTimeMillis() - startTime));
}
public static void main(String[] args) {
sortHashMap();
sortLinkedHashMap();
sortTreeMap();
}
ty-->Mary
qw-->Cole
gfg-->Ray
jhj-->Jan
er-->Eli
gfgf-->Emmy
HashMap遍历花费的时间Time=0
=================
jhj-->Jan
gfg-->Ray
qw-->Cole
gfgf-->Emmy
ty-->Mary
er-->Eli
LinkedHashMap遍历花费的时间Time=1
=============
er-->Eli
gfg-->Ray
gfgf-->Emmy
jhj-->Jan
qw-->Cole
ty-->Mary
TreeMap遍历花费的时间Time=0