Map集合遍历总结

遍历Map集合的方式有两种,如下所示:

第一种:获取所有的key-value中的key组成Set集合,再通过Set集合遍历的方式(加强循环或者迭代器),遍历key,从而通过Map集合中色get方法得到value的值

public class Test4 {
	public static void main(String[] args) {
		Map<String, Integer> scores = new HashMap<String, Integer>();
		scores.put("Tom",100);
		scores.put("Kate", 60);
		
		//Map集合遍历
		//第一种:获取所有的key-value中的key组成Set集合,再通过Set集合遍历的方式(加强循环或者迭代器),遍历key,从而通过Map集合中色get方法得到value的值
		
		//加强循环
		Set<String> names = scores.keySet();
		for (String name : names) {
			int score = scores.get(name);
			System.out.println(score);
		}
		
		//迭代器
		Iterator<String> iterator = names.iterator();
		while(iterator.hasNext()) {
			int score = scores.get(iterator.next());
			System.out.println(score);
		}
	}
}

第二种:将所有的key-value变成一个Entry对象(即用Entry对象包含),再通过Set集合遍历的方式(加强循环或者迭代器),通过Entry对象getValue()得到value的值

public class Test4 {
	public static void main(String[] args) {
		Map<String, Integer> scores = new HashMap<String, Integer>();
		scores.put("Tom",100);
		scores.put("Kate", 60);
		
		//Map集合遍历
		//第二种:将所有的key-value变成一个Entry对象(即用Entry对象包含),再通过Set集合遍历的方式(加强循环或者迭代器),通过Entry对象getValue()得到value的值
		
		//加强循环
		Set<Entry<String, Integer>> entries = scores.entrySet();
		for (Entry<String, Integer> entry : entries) {
			int score = entry.getValue();
			System.out.println(score);
		}
		
		//迭代器
		Iterator<Entry<String, Integer>> iterator =entries.iterator();
		while(iterator.hasNext()) {
			Entry<String, Integer> entry = iterator.next();
			System.out.println(entry.getValue());
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值