loading

Map遍历元素如何按照put顺序输入的元素进行顺序输出

  • Home
  • Blog
  • Map遍历元素如何按照put顺序输入的元素进行顺序输出

Map遍历元素如何按照put顺序输入的元素进行顺序输出

我们利用Map存数,遍历输出的时候希望其按照put的顺序,顺序输出,如何实现呢?其实非常简单,我们常常实现Map的时候,都是采用HashMap,很容易忽略其链表形式的LinkedHashMap(),今天犯了一个容易忽视的错误,先看代码:

public static void main(String[] args) {

Map hashMap = new HashMap();

hashMap.put("1", "aaa");

hashMap.put("2", "bbb");

hashMap.put("3", "ccc");

hashMap.put("4", "ddd");

hashMap.put("5", "eee");

for(int i = 0;i<100;){

for (Map.Entry entry : hashMap.entrySet()) {

System.out.println("hashKey= " + entry.getKey() + "\t" + "hashValue = " + entry.getValue());

}

i++;

System.out.println("\r\n");

}

}

代码非常简单,但是遍历100次输出,结果竟然真的是顺序输出,当时我就纳闷了?HashMap不是无序的吗?

改了改代码:

public static void main(String[] args) {

Map hashMap = new HashMap();

Map linkedHashMap = new LinkedHashMap();

hashMap.put("1", "aaa");

hashMap.put("22", "bbb");

hashMap.put("333", "ccc");

hashMap.put("4444", "ddd");

hashMap.put("55555", "eee");

linkedHashMap.put("6", "老胡");

linkedHashMap.put("77", "小张");

linkedHashMap.put("888", "红中");

linkedHashMap.put("9999", "东风");

linkedHashMap.put("10000", "西");

for (Map.Entry entry : hashMap.entrySet()) {

System.out.println("hashKey= " + entry.getKey() + "\t" + "hashValue = " + entry.getValue());

}

for (Map.Entry entry : linkedHashMap.entrySet()) {

System.err.println("linkKey= " + entry.getKey() + "\t" + "linkValue = " + entry.getValue());

}

}

结果输出果真变成无序的了,想要按照put顺序输出,我们可以采用LinkedHashMap(),它内部有一个链表,保持插入的顺序。迭代的时候,也是按照插入顺序迭代,而且迭代比HashMap快。

结果今天一下子没想到,差点还去写按照key排序的方法,汗颜!