【Java】Map集合中常用方法

|-------------------------------------|---------------|
| 方法名称 | 作用 |
| V put(Key k,V value) | 添加元素 |
| V remove(K key, V value) | 根据键值删除对应的值 |
| void clear() | 清除所有键值元素 |
| boolean containsKey(Object key) | 判断集合中是否包含指定的键 |
| boolean containsValue(Object value) | 判断集合中是否包含指定的值 |
| boolean isEmpty() | 判断集合是否为空 |
| size() | 返回集合中存放元素的个数 |
[Map集合的常用方法]


示例代码

java 复制代码
package com.collection.Demo09;

import java.util.HashMap;
import java.util.Map;

public class Test01 {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<>();
        System.out.println("========put========");
        hashMap.put("mayikt001", "小明");
        hashMap.put("mayikt002", "xiaojun");
        hashMap.put("mayikt003", "xiaoli");
        hashMap.put("mayikt003", "小王"); //键是不允许重复的,这里并不会报错,而是修改K="003"的值为V="mayikt"
        System.out.println(hashMap);//{mayikt002=xiaojun, mayikt001=小明, mayikt003=小王}
        //注意:上面遍历的顺序并不是put插入的顺序------∴元素存取是散列无序的
        System.out.println("========remove========");
        hashMap.remove("mayikt001"); //返回String类型
//        hashMap.remove("mayikt002","xiaojun");//只有键值对 都 存在才可以删除,返回Boolean类型
        hashMap.remove("xiaojun"); //没有这个键 ,执行并不报错
        System.out.println(hashMap);
        System.out.println("========clean========");
//        hashMap.clear();//清空hashMap集合中所有键值对
        System.out.println(hashMap);//{}
        System.out.println("========containsKey========");
        //判断在 hashMap集合中 是否存在 键值=mayikt002, 返回true/false
        System.out.println(hashMap.containsKey("mayikt002"));//true
        System.out.println("========containsValue========");
        System.out.println(hashMap.containsValue("xiaowang"));//false
        System.out.println(hashMap.containsValue("小王"));//true
        System.out.println(hashMap.containsValue("小明"));//false
        System.out.println("========isEmpty========");
        System.out.println(hashMap.isEmpty());//false
        HashMap<String, String> hashMap1 = new HashMap<>();
        System.out.println(hashMap1.size());//0 hashMap1中元素的个数
        HashMap<String, String> hashMap2 = null;
        System.out.println(hashMap1.isEmpty());//true
//        System.out.println(hashMap2.isEmpty());//报错.NullPointerException
    }
}

下一篇文章:

相关推荐
2501_9032386511 分钟前
Spring MVC中环境配置的实战应用
java·spring·mvc·个人开发
奔跑吧邓邓子12 分钟前
【Python爬虫(34)】Python多进程编程:开启高效并行世界的钥匙
开发语言·爬虫·python·多进程
程序员侠客行13 分钟前
Spring事务原理详解 三
java·后端·spring·架构
Heris9939 分钟前
2.22 c++练习【operator运算符重载、封装消息队列、封装信号灯集】
开发语言·c++
----云烟----41 分钟前
C/C++ 中 volatile 关键字详解
c语言·开发语言·c++
mjr1 小时前
设计模式-Java
java·设计模式
零星_AagT1 小时前
Apache-CC6链审计笔记
java·笔记·apache·代码审计
yuanpan1 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
程序员张31 小时前
使用IDEA提交SpringBoot项目到Gitee上
java·gitee·intellij-idea
BanLul1 小时前
进程与线程 (三)——线程间通信
c语言·开发语言·算法