HashMap

复制代码
package Day01;

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

public class HashMap1 {
    public static void main(String[] args) {
        //建一个HashMap对象
        HashMap<Student,String> map = new HashMap<>();
        //创建三个学生对象
        Student student1 = new Student("张三",20);
        Student student2 = new Student("李四",21);
        Student student3 = new Student("王五",22);
        Student student4 = new Student("李四",21);
        //向HashMap中添加对象元素和籍贯
        map.put(student1,"广东省");
        map.put(student2,"云南省");
        map.put(student3,"河北省");
        map.put(student4,"河南省");
        //对元素遍历
        Set<Map.Entry<Student, String>> entries = map.entrySet();
        for(Map.Entry<Student,String> entry:entries){
            Student key = entry.getKey();
            String name = key.getName();
            int age = key.getAge();
            System.out.println(name+","+age+"="+entry.getValue());
        }

    }
}

核心点:如果HashMap的键位置存储的是自定义对象,需要重写equals和hashcode

复制代码
package Day01;

import java.util.*;

public class HashMap2 {
    public static void main(String[] args) {
        //统计ABCD景点想去的人数
        //创建HashMap集合
        HashMap<String,Integer> map = new HashMap<>();
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, "B", "C", "D","A","B","C","A","A","B","C","A","B");
        //遍历集合
        //生成对象的单列数组
        for(int i=0;i<list.size();i++){
            if(map.containsKey(list.get(i))){
                int i1 = map.get(list.get(i)) + 1;
                map.put(list.get(i),i1);
            }else {
                map.put(list.get(i),1);
            }
        }
        //计算集合中最大值
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        int MaxValue = 0;
        for(Map.Entry<String,Integer> entry:entries){
            if(entry.getValue()>MaxValue){
                MaxValue = entry.getValue();
            }
        }
        //因为可能存在两个键值相同的情况
        for(Map.Entry<String,Integer> entry:entries){
            if(entry.getValue()==MaxValue){
                System.out.println(entry.getKey()+" "+entry.getValue());
            }
        }
    }
}
相关推荐
lly2024067 小时前
Bootstrap 警告框
开发语言
2601_949146537 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧7 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX7 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01037 小时前
C++课后习题训练记录Day98
开发语言·c++
爬山算法8 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7258 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎8 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄8 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
YUJIANYUE9 小时前
PHP纹路验证码
开发语言·php