一、需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student),存储三个键值对元素,并遍历

分析:

public class StudentDemo {
    public static void main(String[] args) {
        //创建Map集合对象
        Map m=new HashMap();
        //添加键值对
        m.put("01",new Student("张三"));
        m.put("04",new Student("赵六"));
        m.put("02",new Student("李四"));
        m.put("03",new Student("王五"));
        //遍历集合
        Set> s= m.entrySet();
        //遍历
        for (Map.Entry ss:s){
            //根据键值对对象获取值和key
            String key=ss.getKey();
           Student value=ss.getValue();
            System.out.println(key+","+value.getName());
        }
        System.out.println("------------------------");
        //方式二,通过键找值
        Set m1=m.keySet();
        for (String key :m1){
             Student student =m.get(key);
            System.out.println(key+","+student.getName());
        }
    }
}

二、需求:创建一个HashMap集合,键是学生对象(Student),值是地址(String),存储三个键值对元素,并遍历分析:

public class StudentDemo {
    public static void main(String[] args) {
        //创建集合对象
        Map m=new HashMap();
        //添加键值对
        m.put(new Student("张三",18),"上海");
        m.put(new Student("李四",19),"北京");
        m.put(new Student("王五",20),"上海");
        m.put(new Student("王五",20),"海南");
        //方式一
        //获取所有键值对的集合
        Set> s=m.entrySet();
        //方式一、遍历
        for (Map.Entry mm:s){
            //通过键值对获取对应的值与键
            Student key=mm.getKey();
            String value=mm.getValue();
            System.out.println(key.getName()+","+key.getAge()+value);
        }
        System.out.println("---------------------------------");
        //方式二
        Set key=m.keySet();
        for (Student s1:key){
            String value=m.get(s1);
            System.out.println(s1.getName()+","+s1.getAge()+","+value);
        }
    }
}
本文转载于:https://www.yisu.com/zixun/692418.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。