Map集合常用API复习
1 package Maptest01; 2 3 import java.util.Collection; 4 import java.util.HashMap; 5 import java.util.Map; 6 import java.util.Set; 7 8 /** 9 * FileName: MapDemo01 10 * Author: lps 11 * Date: 2022/4/14 11:07 12 * Sign:刘品水 Q:1944900433 13 */ 14 public class MapDemo01 { 15 public static void main(String[] args) { 16 //添加元素:无序 不重复 无索引 17 //Map<String, Integer> maps = new HashMap<>();//一行经典代码 18 Map<String, Integer> maps = new HashMap<>();//一行经典代码 19 maps.put("刘品水",3); 20 maps.put("枸杞",13); 21 maps.put("Java",1); 22 maps.put("Java",100); 23 maps.put("手机",50); 24 //maps.put(null,null); 25 26 //2.清空集合 27 // maps.clear(); 28 // System.out.println(maps); 29 30 //3.查看是否为空 31 System.out.println(maps.isEmpty()); 32 33 //4.根据键获取值 public V get(Object key) 34 Integer key = maps.get("Java"); 35 System.out.println(key); 36 //System.out.println(maps.get("Java")); 37 38 //5.根据键删除整个元素 (删除键会返回键的值) 39 Integer key1 = maps.remove("手机"); 40 System.out.println(key1); 41 System.out.println(maps); 42 43 //6.判断是否包含某个键 包含返回true 反之 44 System.out.println(maps.containsKey("Java")); 45 boolean mobilephone = maps.containsKey("手机"); 46 System.out.println(mobilephone); 47 48 49 //7.判断是否包含某个值 50 System.out.println(maps.containsValue(13)); 51 52 //8.获取全部键的集合 public Set<K> keyset() 53 Set<String> strings = maps.keySet(); 54 System.out.println(strings); 55 56 //9.获取所有值的集合Collection<V> values(); 57 Collection<Integer> values = maps.values(); 58 System.out.println(values); 59 60 //10.集合的大小 61 int size = maps.size(); 62 System.out.println(size); 63 64 //11.合并其他Map集合 65 HashMap<String, Integer> map1 = new HashMap<>(); 66 map1.put("Java1",50); 67 map1.put("Java2",2); 68 HashMap<String, Integer> map2 = new HashMap<>(); 69 map2.put("Java2",50); 70 map2.put("Java3",2); 71 map1.putAll(map2);//把集合map2的元素拷贝到map1中 72 System.out.println(map1); 73 System.out.println(map2); 74 75 76 } 77 }