Java中的Map集合

Map集合

Map集合的概述和使用

Map集合概述

  • Interface Map<K,V> K: 键的类型;V: 值的类型

  • 将键映射到值的对象;不能包含重复的键;每个键可以映射到最多一个值

  • 举例:学生的学号和姓名

    ​ 1001 张三

    ​ 1002 李四

    ​ 1003 王五

创建Map集合的对象

  • 多态的方式
  • 具体的实现类HashMap
//创建集合对象
Map<String, String> map = new HashMap<String, String>();

map.put("1001", "张三");
map.put("1002", "李四");
map.put("1003", "小明");
map.put("1003", "州总"); //当键重复时,put会将之前键对应的值替换掉

//输出集合对象
System.out.println(map); //{1003=州总, 1002=李四, 1001=张三}

Map集合的基本功能

V put(K key, V value): 添加元素

V remove(Object key): 根据键删除键值对元素

void clear(): 移除所有键值对元素

boolean containsKey(Object key): 判断集合是否包含指定的键

boolean containsValue(Object key): 判断集合是否包含指定的值

boolean isEmpty(): 判断集合是否为空

int size(): 集合的长度,也就是集合中键值对的个数

//创建集合对象
Map<String, String> map = new HashMap<String, String>();

//put: 添加元素
map.put("1001", "张三");
map.put("1002", "李四");
map.put("1003", "王五");

//remove(Object key): 删除指定元素
System.out.println(map.remove("1001")); //张三
System.out.println(map.remove("1004")); //null

//clear(): 移除所以的键值对元素
map.clear();

System.out.println(map.containsKey("1001")); //true
System.out.println(map.containsKey("1004")); //false

System.out.println(map.isEmpty());

System.out.println(map.size());

//输出集合对象
System.out.println(map);

Map集合的获取功能

/*
	Map集合的获取功能:
		V get(Object key): 根据键获取值
		Set<K> keySet(): 获取所有键的集合
		Collection<V> values(): 获取所有值的集合
*/
//创建集合对象
Map<String, String> map = new HashMap<String, String>();

//添加元素
map.put("1001", "小明");
map.put("1002", "张三");
map.put("1003", "李四");

System.out.println(map.get("1001"));
System.out.println(map.get("1004")); //null

Set<String> keySet = map.keySet();
for (String key : keySet) {
	System.out.println(key);
}

Collection<String> values = map.values();
for (String value : values) {
	System.out.println(value);

Map集合的遍历(方式1)

使用keySet()获取到集合中所有的键,在用增强for获取到每一个键,分别使用get(key)获取到每个键对应的值实现遍历。

//创建集合对象
Map<String, String> map = new HashMap<String, String>();

//添加元素
map.put("1001", "张三");
map.put("1002", "李四");
map.put("1003", "王五");

//获取所有键的集合,用keySet()实现
Set<String> keySet = map.keySet();
//遍历键的集合,获取到每一个键,用增强for实现
for (String key : keySet) {
    //根据键去找值,用get(Object key)方法实现
    String value = map.get(key);
    System.out.println("key: " + key + ", value: " + value);
}

Map集合的遍历(方式2)

  • 获取所有键值对对象的集合:

    Set<Map.Entry<K,V>> entrySet(): 获取所有键值对对象的集合

  • 遍历键值对对象的集合,得到每一个键值对对象

    用增强for实现,得到每一个Map.Entry

  • 根据键值对对象获取键和值

    • 用getKey()获取键
    • 用getValue()获取值
//创建集合对象
Map<String, String> map = new HashMap<String, String>();

//添加元素
map.put("1001", "张三");
map.put("1002", "李四");
map.put("1003", "王五");

//获取所有键值对对象的集合
Set<Map.Entry<String, String>> entries = map.entrySet();

//遍历键值对对象的集合,得到每一个键值对对象
for (Map.Entry<String, String> entry : entries) {
    //根据键值对对象获取键和值
    System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}

HashMap集合存储学生对象并遍历

public class HashMapDemo {
    public static void main(String[] args) {
        //创建集合对象
        HashMap<String, Student> hashMap = new HashMap<>();

        //添加元素
        Student s1 = new Student("张三", 16);
        Student s2 = new Student("李四", 20);
        Student s3 = new Student("王五", 22);

        hashMap.put("1001", s1);
        hashMap.put("1002", s2);
        hashMap.put("1003", s3);

        //遍历集合
        //方式1:键找值
        Set<String> keySet = hashMap.keySet();
        for (String key : keySet) {
            Student student = hashMap.get(key);
            System.out.println(key + ", " + student.getName() + ", " + student.getAge());
        }
        System.out.println("--------");
        
        //方式2:键值对对象找键和值
        Set<Map.Entry<String, Student>> entries = hashMap.entrySet();

        for (Map.Entry<String, Student> entry : entries) {
            String key = entry.getKey();
            Student student = entry.getValue();
            System.out.println(key + ", " + student.getName() + ", " + student.getAge());
        }
    }
}

HashMap集合存储学生对象并遍历

需求:创建一个HashMap集合,键是学生对象(Student),值是居住地(String)。存储多个键值对元素,并遍历。

要求:保证键的唯一性,如果学生对象的成员变量值相同,我们就认为是同一个对象。

//创建集合对象
HashMap<Student, String> hashMap = new HashMap<Student, String>();

//添加元素
Student s1 = new Student("张三", 10);
Student s2 = new Student("李四", 20);
Student s3 = new Student("王五", 18);
Student s4 = new Student("王五", 18);

hashMap.put(s1, "北京");
hashMap.put(s2, "上海");
hashMap.put(s3, "深圳");
hashMap.put(s4, "长沙");

//遍历
Set<Student> students = hashMap.keySet();
for (Student student : students) {
    String address = hashMap.get(student);
    System.out.println(student.getName() + ", " + student.getAge() + ", " + address);
}

在Student类中重写hashCode()方法和equals()方法

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Student student = (Student) o;

    if (age != student.age) return false;
    return name != null ? name.equals(student.name) : student.name == null;
}

@Override
public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + age;
    return result;
}

ArrayList集合存储HashMap元素并遍历

public static void main(String[] args) {
    //创建ArrayList集合
    ArrayList<HashMap<String, String>> array = new ArrayList<>();

    HashMap<String, String> hashMap1 = new HashMap<>();
    hashMap1.put("1001", "张三");
    hashMap1.put("1002", "李四");
    HashMap<String, String> hashMap2 = new HashMap<>();
    hashMap2.put("1", "北京");
    hashMap2.put("2", "上海");
    HashMap<String, String> hashMap3 = new HashMap<>();
    hashMap3.put("小明", "18");
    hashMap3.put("小红", "20");

    array.add(hashMap1);
    array.add(hashMap2);
    array.add(hashMap3);

    for (HashMap<String, String> hashMap : array) {
        Set<String> keySet = hashMap.keySet();
        for (String key : keySet) {
            String value = hashMap.get(key);
            System.out.println("key: " + key + ", value: " + value) ;
        }
    }
}

HashMap集合存储ArrayList元素并遍历

需求:创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String, 值是ArrayList,每一个ArrayList的元素是String,并遍历

//创建集合对象
HashMap<String, ArrayList<String>> hashMap = new HashMap<>();

ArrayList<String> array1 = new ArrayList<>();
array1.add("诸葛亮");
array1.add("赵云");
hashMap.put("三国演义", array1);

ArrayList<String> array2 = new ArrayList<>();
array2.add("令狐冲");
array2.add("岳不群");
hashMap.put("笑傲江湖", array2);

ArrayList<String> array3 = new ArrayList<>();
array3.add("小明");;
array3.add("小红");
hashMap.put("1003", array3);

Set<Map.Entry<String, ArrayList<String>>> entries = hashMap.entrySet();
for (Map.Entry<String, ArrayList<String>> entry : entries) {
    System.out.println("key: " + entry.getKey());
    ArrayList<String> array = entry.getValue();
    for (String s : array) {
        System.out.println(s);
    }
}

案例—统计字符串中每个字符出现的次数

需求:键盘录入一个字符串,要求统计字符串中每个字符出现的次数。

​ 举例:键盘录入"aababcabcdabcde" 在控制台输出:“a(5)b(4)c(3)d(2)e(1)”

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入字符串:");
    String s = sc.nextLine();

    //创建HashMap集合
    HashMap<Character, Integer> hashMap = new HashMap<>();

    for (int i = 0; i < s.length(); i ++) {
        char key = s.charAt(i);

        Integer value = hashMap.get(key);

        if (value == null) {
            hashMap.put(key, 1);
        } else {
            value ++;
            hashMap.put(key, value);
        }
    }

    //遍历hashMap集合
    StringBuilder sb = new StringBuilder();

    Set<Character> keySet = hashMap.keySet();
    for (Character key : keySet) {
        Integer value = hashMap.get(key);
        sb.append(key).append("(").append(value).append(")");
    }

    String result = sb.toString();
    System.out.println(result);
}

让集合按照键进行排序,要使用TreeMap集合:

Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串:");
        String s = sc.nextLine();

        //创建HashMap集合
//        HashMap<Character, Integer> hashMap = new HashMap<>();
        TreeMap<Character, Integer> hashMap = new TreeMap<>();

        for (int i = 0; i < s.length(); i ++) {
            char key = s.charAt(i);

            Integer value = hashMap.get(key);

            if (value == null) {
                hashMap.put(key, 1);
            } else {
                value ++;
                hashMap.put(key, value);
            }
        }

        //遍历hashMap集合
        StringBuilder sb = new StringBuilder();

        Set<Character> keySet = hashMap.keySet();
        for (Character key : keySet) {
            Integer value = hashMap.get(key);
            sb.append(key).append("(").append(value).append(")");
        }

        String result = sb.toString();
        System.out.println(result);

输出结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hF2SjGKJ-1628749863757)(C:\Users\zhou\AppData\Roaming\Typora\typora-user-images\image-20210812142953281.png)]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值