Map的遍历几种方式

		Mapmap=new HashMap<>();
		map.put("name","li");
		map.put("age","24");
		// 第一种
		for (String key:map.keySet()){
			System.out.println(map.get(key));
		}
		// 第二种
		Iterator> iter=map.entrySet().iterator();
		while (iter.hasNext()){
			System.out.println(iter.next().getValue());
		}
		// 第三种
		for (Map.Entryen:map.entrySet()){
			System.out.println(en.getValue());
		}
        Map hm = new HashMap();
        Student stu1 = new Student(1,"MapTom");
        Student stu2 = new Student(2,"MapJack");
        Student stu3 = new Student(3,"MapKoby");
        hm.put("1", stu1);
        hm.put("2", stu2);
        hm.put("3", stu3);
        /*第一种  先将map对象转成set,然后再转为迭代器*/
        Iterator> it = hm.entrySet().iterator();
        while (it.hasNext()) {
            //System.out.println(it.next().getKey());
            System.out.println(it.next().getValue().getName());
        }
        /*第二种 先将map转为set类型的key值集合,然后转为迭代器*/
        Iterator it2 = hm.keySet().iterator();
        while(it2.hasNext()){
        /*  System.out.println(it2.next());*/
            System.out.println(hm.get(it2.next()).getName());
        }

 

你可能感兴趣的:(Java面试小知识点)