Map集合
Map集合介绍是双列集合每个元素是一对值每一对值也叫键值对对象。特点针对键而言。HashMap无序、不重复、无索引。底层基于哈希表注意HashMap集合的键和值可以是null。LinkedHashMap有序、不重复、无索引。底层基于哈希表和链表TreeMap无序、不重复、无索引、键可排序(键如果是自定义类类型则需要定义排序规则)。底层基于红黑树结构创建对象MapString,Integer map new HashMap();常用方法public V put(K key, V value) 添加/修改元素返回被修改的元素值旧值。如果是添加则返回null。public V get(Object obj) 根据键获取对应值public V remove(Object key) 根据键删除整个元素,返回被删除的value值。public boolean containsKey(Object value) 判断是否包含某个键public SetK keySet() 获取全部键的集合public static void main(String[] args) { MapString, Integer map new HashMap(); //public V put(K key, V value) 添加/修改元素 map.put(张三, 18); map.put(李四, 19); map.put(王五, 20); //public int size() 获取集合的大小 int s map.size(); System.out.println(map.size() s); //public void clear() 清空集合 map.clear(); System.out.println(map map); //public boolean isEmpty() 判断集合是否为空为空返回true boolean empty map.isEmpty(); System.out.println(map.isEmpty() empty); //public V get(Object obj) 根据键获取对应值 Integer i map.get(张三); System.out.println(map.get(\张三\) i); //public V remove(Object key) 根据键删除整个元素 Integer remove map.remove(张三); System.out.println(map map); //public boolean containsKey(Object key) 判断是否包含某个键 boolean containsKey map.containsKey(张三); System.out.println(map.containsKey(\张三\) containsKey); //public boolean containsValue(Object key) 判断是否包含某个值 boolean b map.containsValue(18); System.out.println(map.containsValue(18) b); //public SetK keySet() 获取全部键的集合 SetString strings map.keySet(); System.out.println(map.keySet() strings); //public CollectionV values() 获取全部值的集合 CollectionInteger values map.values(); System.out.println(map.values() values); }遍历集合public static void main(String[] args) { MapString, Integer map new HashMap(); map.put(张三, 18); map.put(李四, 19); map.put(王五, 20); /* Map集合的遍历方式一键找值 public SetK keySet() 获取所有键的集合 public V get(Object key) 根据键获取其对应的值 */ SetString strings map.keySet(); for (String s : strings) { Integer i map.get(s); System.out.println(s i); } /* Map集合的遍历方式二键值对 Map集合提供的方法 SetMap.EntryK, V entrySet() 获取所有“键值对”的集合 Map.Entry对象提供的方法 K getKey() 获取键 V getValue() 获取值 */ SetMap.EntryString, Integer entries map.entrySet(); for (Map.EntryString, Integer entry : entries) { System.out.println(entry.getKey() entry.getValue()); } /* Map集合的遍历方式三forEach()lambda表达式 default void forEach(BiConsumer? super K, ? super V action) 结合lambda遍历Map集合 */ map.forEach((s, integer) - System.out.println(s integer)); map.forEach(new BiConsumerString, Integer() { Override public void accept(String s, Integer integer) { System.out.println(s integer); } }); }