Map遍历及获取值与键的两种方式

/**
 *    /*
         * 练习一:
         * 学生对象(姓名,年龄)都有自己的归属地,既然有对应关系。
         * 将学生对象和归属地存储到map集合中。
         * 注意:同姓名同年龄视为重复的键。
 
 */
public class Practise1 {
 
    public static void main(String[] args) {
        /*创建Map集合*/
        Map<Student,String> classMap = new HashMap<Student,String>();
        classMap.put(new Student("小明",15), "上海");
        classMap.put(new Student("小李",15), "沈阳");
        classMap.put(new Student("小徐",13), "武汉");
        classMap.put(new Student("小明",15), "上海");        //视为重复的键
        classMap.put(new Student("天天",14), "武汉");
        classMap.put(new Student("刚刚",12), "河北");
 
 
        /*遍历的三种方法*/
        //1.通过遍历key,获取value
        Set<Student> allStudents = classMap.keySet(); 
 
        for(Student stu: allStudents){
            /*遍历获得到的所有key键值*/
            System.out.println(stu);
            /*通过遍历key,获得对应的value值的方法*/
            System.out.println(classMap.get(stu));
        }
        System.out.println("/*-----通过迭代key 获取对应的value--------*/");
        /*利用Iterator迭代*/
        Iterator<Student> it = allStudents.iterator();
        while(it.hasNext()){
            Student key = it.next();
            /*通过迭代key 获取对应的value*/
            System.out.println(key);
            System.out.println(classMap.get(key));
        }
 
        /*2.遍历键值对*/
        Set<Entry<Student,String>> entrys = classMap.entrySet();
 
        /*entrys获取到了classMap中所有的键值对*/
        for(Entry<Student,String> ent : entrys){
            System.out.println("键的获取: "+ent.getKey());
            System.out.println("值的获取: "+ent.getValue());
        }
    }
}

转载于:https://www.cnblogs.com/zyjcxc/p/5463570.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值