HashMap集合遍历

240 阅读1分钟

1628478766221.jpeg--- HQH

一.Map集合创建对象

Map集合以两种不同或相同数据类型的元素作为键和对且Map中存储的元素都是成对出现的

public class Text {
    public static void main(String[] args) {
        //HashMap集合存储的两种数据类型必须是引用数据类型
        HashMap<String, String> map1 = new HashMap<>();
        map1.put("黄", "赵");
        HashMap<Integer, String> map2 = new HashMap<>();
        map2.put(2, "黄");
        HashMap<Double, Character> map3 = new HashMap<>();
        map3.put(15.00, 'a');
        HashMap<Student, Student> map4 = new HashMap<>();
        Student stus1 = new Student();
        Student stus2 = new Student();
        map4.put(stus1, stus2);

二.Map集合的遍历

1. 键找值

我们可以把Map看作是一个父子关系的集合 ,把父亲看作“”,儿子看作“”。先把所有的父亲()集合在一起,然后通过父亲去找儿子(键找对)的方式得到Map集合里的元素。

public class Text {
    public static void main(String[] args) {
        HashMap<String, String> map1 = new HashMap<>();
        //添加元素
        map1.put("孙坚","孙策");
        map1.put("陆逊","陆抗");
        map1.put("岳飞","岳云");
        //获取所有父亲的集合(键),用keySet方法实现
        Set<String> keySet=map1.keySet();
        //用增强for遍历出每一个父亲(键)
        for (String key:keySet){
            //最后根据父亲找儿子,用map集合的get(Object key)方法,再用一个变量接受
            String value=map1.get(key);
            System.out.println(key+","+value);

输出结果

image.png

2.键值对对象找键与值

我们可以把Map集合看作是一个夫妻对(键值对)的集合,先获取所有的结婚证的集合,然后再通过结婚证找到相应的丈夫()和妻子(

//添加元素
HashMap<String, String> hm = new HashMap<>();
hm.put("杨过", "小龙女");
hm.put("郭靖", "黄蓉");
hm.put("张无忌", "赵敏");
//获取所有键值对对象的集合
//Set<Map.Entry<K,V>>方法可以返回此地图包含的映射Set视图
Set<Map.Entry<String, String>> entrySet = hm.entrySet();
//遍历集合对象,获取每个键值对对象
for (Map.Entry<String, String> me : entrySet) {
    //用getKey和getValue方法,根据键值对对象得到键与值
    String key = me.getKey();//键
    String value = me.getValue();//值
    System.out.println(key + "," + value);
}

输出结果

image.png