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());
            }
        }
    }
}
相关推荐
就叫飞六吧2 小时前
Spring 框架中的 Bean 继承:`parent` 属性 (XML配置)
xml·java·spring
故渊ZY2 小时前
SpringBean核心机制与实战应用详解
java·spring
专注VB编程开发20年2 小时前
C# int*指向 int 的指针类型(unsafe 上下文)
java·开发语言·c#
计算机学姐2 小时前
基于SSM的生鲜食品商城系统【2026最新】
java·vue.js·后端·mysql·java-ee·tomcat·mybatis
要站在顶端2 小时前
iOS自动化测试全流程教程(基于WebDriverAgent+go-ios)
开发语言·ios·golang
liwulin05062 小时前
【PYTHON】python venv创建虚拟环境,非conda
开发语言·python·conda
fengfuyao9852 小时前
基于MATLAB的支持向量机在故障诊断中的应用例程
开发语言·支持向量机·matlab
Watermelo6172 小时前
【简单快速】windows中docker数据如何从C盘迁移到其他盘
java·运维·docker·容器·运维开发·devops·空间计算
C++业余爱好者2 小时前
Java 中的数据结构详解及应用场景
java·数据结构·python