【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
    }
}

下一篇文章:

相关推荐
0xDevNull1 分钟前
Spring 核心教程:@Component vs @Bean 深度解析
java·后端
Michelle80232 分钟前
R语言 for循环
开发语言·r语言
小碗羊肉4 分钟前
【从零开始学Java | 第三十二篇】方法引用(Method Reference)
java·开发语言
玖釉-8 分钟前
C++ 硬核剖析:if 语句中的“双竖杠” || 到底怎么运行的?
开发语言·c++
满满和米兜9 分钟前
【Java基础】- 集合-HashSet与TreeSet
java·开发语言·算法
zhangzeyuaaa18 分钟前
Python推导式(Comprehensions)
开发语言·python
m0_7167652318 分钟前
数据结构三要素、时间复杂度计算详解
开发语言·数据结构·c++·经验分享·笔记·算法·visual studio
卷心菜狗19 分钟前
Python进阶基础--面向对象编程(OOP)
开发语言·python
开心码农1号21 分钟前
RabbitMQ 生产运维命令大全
linux·开发语言·ruby
网安INF21 分钟前
数据结构第二章复习:线性表
java·开发语言·数据结构