Java Map集合的使用

Map集合概述

Map集合分类

  • 单列集合

    单列集合一次存储一个元素
    在这里插入图片描述

  • 双列集合

    双列集合一次添加两个元素(一对数据)
    在这里插入图片描述

Map集合总结

  • Interface Map<K, V> K:键的数据类型,V:值的数据类型
  • 键不能重复,值可以重复
  • 键和值一一对应,每一个键只能找到自己对应的值
  • (键+值)这个整体 称为 “键值对”,或 “键值对” 对象,在 Java 中称为 “Entry” 对象
  • 举例说明:学生的学号和姓名
    • 20001 -> 张三
    • 20002 -> 李四
    • 20003 -> 王五

Map集合(HashMap)的使用

Map对象的创建

  • Map对象的创建

    • 多态的方式
    • 具体的实现类 HashMap
  • 基本使用

    Map<String, String> map = new HashMap<>();
    		
    map.put("20001", "张三");
    map.put("20002", "李四");
    map.put("20003", "王五");
    map.put("20004", "赵六");
    
    System.out.println(map); // {20004=赵六, 20003=王五, 20002=李四, 20001=张三}
    

Map集合常用方法

方法名说明
V put(K key, V value)添加元素
V remove(Object key)根据键删除键值对元素
void clear()移除所有键值对元素
boolean containsKey(Object key)判断集合会否包含指定的键
boolean containsValue(Object value)判断集合会否包含指定的值
boolean isEmpty()判断集合是否为空
int size()返回集合的长度,也就是集合中键值对的个数
  • put() 方法

    Map<String, String> map = new HashMap<>();
    String m1 = map.put("20001", "张三");
    System.out.println(m1); # null
    System.out.println("---------");
    String m2 = map.put("20001", "李四");
    System.out.println(m2); # 张三
    System.out.println(map); # {20001=李四}
    

    使用put()方法添加元素时,如果所添加的键不存在则添加到map对象里,如果存在则覆盖,然后返回原来的所对应键的值

  • remove() 方法

    map.put("20001", "张三");
    String s = map.remove("20001");
    System.out.println(s); // 张三
    System.out.println(map); // {}
    

    使用remove()方法删除元素会返回所删除键的值

  • clear() 方法

    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    map.clear();
    System.out.println(map); // {}
    

    清空所有元素

  • containsKey() 方法

    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    boolean result1 = map.containsKey("20001");
    boolean result2 = map.containsKey("20002");
    System.out.println(result1); // true
    System.out.println(result2); // false
    

    判断对象里是否包含指定的键,如果包含则返回true,否则返回false

  • containsValue() 方法

    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    boolean result1 = map.containsValue("张三");
    boolean result2 = map.containsValue("李四");
    System.out.println(result1); // true
    System.out.println(result2); // false
    

    判断对象里是否包含指定的值,如果包含则返回true,否则返回false

  • inEmpty() 方法

    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    boolean result1 = map.isEmpty();
    System.out.println(result1); // false
    map.clear();
    boolean result2 = map.isEmpty();
    System.out.println(result2); // true
    

    判断集合是否为空,不为空返回false,否则返回true

  • size() 方法

    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    int size = map.size();
    System.out.println(size); // 1
    

    返回集合的长度(集合的元素个数)

遍历Map集合对象

  • 第一种遍历方式

    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    map.put("20002", "李四");
    map.put("20003", "王五");
    map.put("20004", "赵六");
    // 获取map对象的所有键
    Set<String> keys = map.keySet();
    // 使用增强 for 遍历 map 对象
    for(String key : keys){
        // 通过具体的 key 来获取对应的值
        String value = map.get(key);
        System.out.println(key + ":" + value);
    

    通过 keySet() 方法获取集合的键,然后通过增强 for 去遍历键,从而获取对应键的值

  • 第二种遍历方式

    方法名说明
    Set <Map.Entry<k, v> > entrySet()获取所有键值对对象的集合
    K getKey()获取键
    K getValue()获取值
    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    map.put("20002", "李四");
    map.put("20003", "王五");
    map.put("20004", "赵六");
    // 首先获取所有键值对对象
    Set<Map.Entry<String, String>> entries = map.entrySet();
    for (Map.Entry<String, String> entry : entries) {
        // 得到每一个键值对对象
        String key = entry.getKey();
        String value = entry.getValue();
        System.out.println(key + ":" + value);
    }
    
  • 第三种遍历方式

    Map<String, String> map = new HashMap<>();
    map.put("20001", "张三");
    map.put("20002", "李四");
    map.put("20003", "王五");
    map.put("20004", "赵六");
    // 使用forEach, 传递lambda表达式
    map.forEach((String key, String value) -> {
        System.out.println(key + ":" + value);
    });
    

案例

需求:创建一个HashMap集合,是学生对象(Student),是家庭地址所在的省。存储两个元素并遍历

  • Student

    package com.cmy.mapdemo;
    
    import java.util.Objects;
    
    /**
     * @author chenmingyong
     */
    public class Student {
    	String name;
    	int age;
    	
    	public Student() {
    	}
    	
    	public Student(String name, int age) {
    		this.name = name;
    		this.age = age;
    	}
    	
    	@Override
    	public boolean equals(Object o) {
    		if (this == o) return true;
    		if (o == null || getClass() != o.getClass()) return false;
    		Student student = (Student) o;
    		return age == student.age &&
    				       Objects.equals(name, student.name);
    	}
    	
    	@Override
    	public int hashCode() {
    		return Objects.hash(name, age);
    	}
    	
    	public String getName() {
    		return name;
    	}
    	
    	public void setName(String name) {
    		this.name = name;
    	}
    	
    	public int getAge() {
    		return age;
    	}
    	
    	public void setAge(int age) {
    		this.age = age;
    	}
    	
    	@Override
    	public String toString() {
    		return "Student{" +
    				       "name='" + name + '\'' +
    				       ", age=" + age +
    				       '}';
    	}
    }
    
    
  • 测试类

    package com.cmy.mapdemo;
    
    import java.util.HashMap;
    
    /**
     * @author chenmingyong
     */
    public class MyMap {
    	public static void main(String[] args) {
    		// 创建HashMap集合对象
    		HashMap<Student, String> stu = new HashMap<>();
    		// 创建学生对象
    		Student student1 = new Student("张三", 18);
    		Student student2 = new Student("李四", 20);
    		// 把学生对象添加到集合里
    		stu.put(student1, "海南");
    		stu.put(student2, "广州");
    		// 遍历stu集合对象
    		stu.forEach((Student Key, String value) -> {
    			System.out.println(Key + ":" + value);
    		});
    	}
    }
    
    

    因为涉及到把类作为 HashMap 对象的键,Student 类得重写 equals() 方法和 hashCode() 方法

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员陈_明勇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值