//LinkedHashMap可以记住元素放入的顺序(有序),hashmap是无序集合 public static void main(String[] args) { HashMap<String,String> linkHashMap = new LinkedHashMap<>(); linkHashMap.put("4","a"); linkHashMap.put("3","b"); linkHashMap.put("2","d"); linkHashMap.put("1","c"); HashMap<String,String> map = new HashMap(); map.put("4","a"); map.put("3","b"); map.put("2","d"); map.put("1","c"); System.out.println("hashmap输出结果"); map.forEach((k, v) -> print(k, v)); System.out.println("linkHashMap输出结果"); linkHashMap.forEach((k,v) -> print(k,v)); } public static void print(String k, String v) { System.out.println("k:" + k + ",v:" + v); }
=======================================
hashmap输出结果
k:1,v:a
k:2,v:b
k:3,v:d
k:4,v:c
linkHashMap输出结果
k:4,v:a
k:3,v:b
k:2,v:d
k:1,v:c