Java 有序的Map —— LinkedHashMap

最近项目中返回 json 用到了 key-value 的格式,而 HashMap 是无序的,则需要用到 LinkedHashMap

一、无序的 HashMap


Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put("name1", "value1");
hashMap.put("name2", "value2");
hashMap.put("name3", "value3");
Set<Entry<String, String>> set = hashMap.entrySet();
Iterator<Entry<String, String>> iterator = set.iterator();
while(iterator.hasNext()) {
     
     Entry<String, String> entry = iterator.next();
     String key = (String) entry.getKey();
     String value = (String) entry.getValue();
     System.out.println("key:" + key + ", value:" + value);
}

可以看到输出结果并不是按数据插入的顺序的。

key:name3, value:value3
key:name2, value:value2
key:name1, value:value1

二、有序的 LinkedHashMap


Map<String, String> hashMap = new LinkedHashMap<String, String>();
hashMap.put("name1", "value1");
hashMap.put("name2", "value2");
hashMap.put("name3", "value3");
Set<Entry<String, String>> set = hashMap.entrySet();
Iterator<Entry<String, String>> iterator = set.iterator();
while(iterator.hasNext()) {
     
     Entry<String, String> entry = iterator.next();
     String key = (String) entry.getKey();
     String value = (String) entry.getValue();
     System.out.println("key:" + key + ", value:" + value);
}

可以看到输出结果为我们插入的顺序 。

key:name1, value:value1
key:name2, value:value2
key:name3, value:value3

你可能感兴趣的:(Java,LinkedHashMap,Map,HashMap)