Map結合也稱為“鍵值對集合”,格式:{key1=value1,key2=value2....}
Map集合的特點:
鍵唯一:在Map集合中,鍵(key)是唯一的,不能有重復的鍵。如果嘗試插入一個已經存在的鍵,新的值會覆蓋舊的值。
值可重復:與鍵不同,值(value)可以重復。鍵和值時一一對應的,每個鍵只能找到自己對應的值。
Map集合的常用方法:
Map是雙列集合的祖宗,它的功能是全部雙列集合都可以繼承過來使用的。
常用實現類:
1.HashMap(由鍵決定特點):無序、不重復、無索引;
2.LInkedHashMap(由鍵決定特點):有序、不重復、無索引;
3.TreeMap(由鍵決定特點):按默認大小升序、不重復、無索引;
Map集合的遍歷方式:
1.鍵找值:先獲取Map集合全部的鍵,再通過遍歷鍵來找值。
通過Set集合存儲Map集合所有的鍵,然后再通過遍歷Set集合提取值
2.鍵值對:把"鍵值對"看成一個整體進行遍歷
Map提供的方法:Set<Map.Entry<K(類型),V(類型)> entrySet()> 獲取所有鍵值對的集合(Map.Entry<K,V>是一個整體類型)
也就是這個方法將Map集合中的鍵值對包裝成一個整體對象存到成Set集合,用getKey()和getValue()兩個方法獲取鍵值對。
3.Lambda表達式:jdk1.8開始之后的新技術(簡單)
需要用到的方法:default void forEach(BiConsumer<? super K,? super V> action)結合lambda遍歷Map集合。?
代碼演示:
public class test1 {public static void main(String[] args) {Map<String,Integer> map = new HashMap<>();map.put("小王",18);map.put("小李",19);map.put("小張",20);map.put("小宋",19);map.put("小王",19);System.out.println(map);//System.out.println(map.get("小王"));Set<String> set = map.keySet();//1.鍵找值將map的鍵添加到set中,遍歷setfor(String key:set){System.out.print(key+"="+map.get(key)+" ");}//2.鍵值對:Set<Map.Entry<String,Integer>> entrySet= map.entrySet();for(Map.Entry<String,Integer> entry:entrySet){System.out.print(entry.getKey()+"="+entry.getValue()+" ");}System.out.println();//3.Lambda表達式:map.forEach(new BiConsumer<String, Integer>() {@Overridepublic void accept(String s, Integer integer) {System.out.print(s+"="+integer);}});//簡化后map.forEach((s,integer)-> System.out.print(s+"="+integer));}
}
Map常用集合的實現類
底層實現原理本質上和Set集合一樣,實際上:原來學的Set系列集合的底層就是基于Map實現的,只是Set集合中的元素只要鍵數據,不要值數據而已
HashSet底層原理是HashMap
LinkedHashSet底層原理是LinkedHashMap
TreeSet底層原理是TreeMap