Map集合
Map集合介绍:
是双列集合,每个元素是一对值,每一对值也叫键值对对象。
特点:针对键而言。
HashMap:无序、不重复、无索引。底层基于哈希表
注意:HashMap集合的键和值可以是null。
LinkedHashMap:有序、不重复、无索引。底层基于哈希表和链表
TreeMap:无序、不重复、无索引、键可排序(键如果是自定义类类型,则需要定义排序规则)。底层基于红黑树结构
创建对象:
Map<String,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 Set<K> keySet() 获取全部键的集合
public static void main(String[] args) { Map<String, 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 Set<K> keySet() 获取全部键的集合 Set<String> strings = map.keySet(); System.out.println("map.keySet() = " + strings); //public Collection<V> values() 获取全部值的集合 Collection<Integer> values = map.values(); System.out.println("map.values() = " + values); }
遍历集合:
public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("张三", 18); map.put("李四", 19); map.put("王五", 20); /* Map集合的遍历方式一:键找值 public Set<K> keySet() 获取所有键的集合 public V get(Object key) 根据键获取其对应的值 */ Set<String> strings = map.keySet(); for (String s : strings) { Integer i = map.get(s); System.out.println(s + " = " + i); } /* Map集合的遍历方式二:键值对 Map集合提供的方法 Set<Map.Entry<K, V>> entrySet() 获取所有“键值对”的集合 Map.Entry对象提供的方法 K getKey() 获取键 V getValue() 获取值 */ Set<Map.Entry<String, Integer>> entries = map.entrySet(); for (Map.Entry<String, 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 BiConsumer<String, Integer>() { @Override public void accept(String s, Integer integer) { System.out.println(s + " = " + integer); } }); }