【Java】Map集合的几种遍历方式

【前言】

在这里与大家分享一下Map集合的几种遍历方式,虽然工作过一年多的时间了,但是我还是觉集合遍历是很常用的,而且Map集合遍历容易混淆遗忘。这里与大家一起温习一下。

public class Test1 {
	public static void main(String[] args) {
		// 1.定义HashMap集合,键为Student对象,值为String类型的对象,表示地址
		HashMap<Student, String> map = new HashMap<>();
		map.put(new Student("张三", 20, 15), "北京");
		map.put(new Student("李四", 20,20), "南京");
		map.put(new Student("王五", 20,45), "上海");
		map.put(new Student("赵六", 20,56), "广州");
		map.put(new Student("孙七", 20,78), "深圳");
	//遍历方式一:增强for循环(entry)
		for(Map.Entry<Student, String> entry :map.entrySet()){
			System.out.println(entry.getKey()+""+entry.getValue());
		}
	//遍历方式二:增强for循环(keySet)
		System.out.println("--------------------------------------------");
		for(Student student : map.keySet()){
			String address = map.get(student);
			System.out.println(student+"::"+address);

		}
		//遍历集合方式三、迭代器
		System.out.println("---------------------------------");
		Set<Map.Entry<Student,String>> set = map.entrySet();
		Iterator<Map.Entry<Student, String>> it = set.iterator();
		while(it.hasNext()){
			Map.Entry<Student,String> entry = it.next();
			System.out.println(entry.getKey() + "::" + entry.getValue());
		
		}
		// 遍历方式四:迭代器(通过keySet())
		System.out.println("-----------------------------------------");
		Set<Student> keySet = map.keySet();
		Iterator<Student> it2 =keySet.iterator();
		while(it2.hasNext()){
			Student student = it2.next();
			String address = map.get(student);
			System.out.println(student +"::"+address);
		}
	}

执行结果:


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值