Map集合常用API

152 阅读1分钟
/**      Map<String,Integer> maps = new HashMap<>();
     //   maps.put(); 添加元素
        maps.put("iPhone13ProMax",1);
        maps.put("麻辣王子",100);
        maps.put("鲜牛奶",3);
       maps.put("麻辣王子",8);//如果Map集合里的键重复,重复的新元素会覆盖老元素
        System.out.println(maps);

   //   maps.clear(); 清空集合元素
      maps.clear();
      System.out.println(maps);

   //  maps.isEmpty(); 判断集合是否为空,为空返回true 反之false
      System.out.println(maps.isEmpty());

     // maps.get(); 根据键获取对应的值,如果集合没有该键返回null
      System.out.println(maps.get("麻辣王子"));
      System.out.println(maps.get("麻辣王子2"));//null

    //    maps.remove(); 根据键删除整个元素(删除键会返回对应的值)
      System.out.println(maps.remove("麻辣王子"));
      System.out.println(maps);

      //  maps.containsKey() 判断是否包含某个键 包含返回true 反之false
        System.out.println(maps.containsKey("鲜牛奶"));//true
        System.out.println(maps.containsKey("鲜牛奶2"));//false

      //  maps.containsValue 判断是否包含某个值 包含返回true 反之false
       System.out.println(maps.containsValue(3));//true
       System.out.println(maps.containsValue(2));//false
       //获取全部的键
        Set<String> keys = maps.keySet();
       System.out.println(keys);
      // 获取全部的值
        Collection<Integer> value = maps.values();
        System.out.println(value);
      // 获取集合的大小
        System.out.println(maps.size());
**/
/**
       //map1.putAll(map2);     合并其他Map集合
        Map<String,Integer> map1 = new HashMap<>();
        map1.put("java1",1);
        map1.put("java2",10);
        Map<String,Integer> map2 = new HashMap<>();
        map2.put("java2",100);
        map2.put("java3",88);
        map1.putAll(map2);//将map2的值拷贝到map1
        System.out.println(map1);
**/