Map集合的两种遍历方式

Map集合遍历一

Map的遍历方式:键找值方式

Map接口定义方法:Set keySet(),Map集合的键取出,存储在Set集合

/*
 * Map集合方法keySet()遍历
 * 步骤:
 * 		1.Map集合方法keySet()获取 存储键的Set集合
 * 		2.遍历Set集合
 * 		3.取出Set集合的元素,是Map的键
 * 		4.Map集合键,找值
 */
public class MapDemo02 {
	public static void main(String[] args) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("abc", 123);
		map.put("bcd", 124);
		map.put("cde", 125);
		
		//1.Map集合方法keySet()获取 存储键的Set集合
		Set<String> set = map.keySet();
		//2.遍历Set集合
		Iterator<String> it = set.iterator();
		while(it.hasNext()) {
			//3.取出Set集合的元素,是Map的键
			String key = it.next();
			//4.Map集合键,找值
			Integer value = map.get(key);
			System.out.println(key+"="+value);
		}
	}
}

Map集合遍历二

键值对的映射关系遍历:Map.Entry接口,实现类对象表示了键值对的对应关系,拿到Map.Entry接口实现类对象.

  • Entry接口的方法
    • K getKey()取出集合中的键
    • V getValue()取出集合中的值
  • Map接口定义的方法
    • Set<Map.Entry<K,V>> entrySet() 集合中的键值对映射关系对象,Entry接口对象,存储在Set集合
/*
 * Map集合的遍历,键值对的映射关系
 * 步骤:
 * 		1.Map集合方法的entrySet() 获取到Entry接口实现类对象,存储Set集合
 * 		2.遍历Set集合
 * 		3.取出Set集合中的元素,是Entry接口的实现类对象(键值对的对应关系)
 * 		4.Entry接口对象,调用方法getKey(),getValue()
 */
public class MapDemo03 {
	public static void main(String[] args) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("abc", 123);
		map.put("bcd", 124);
		map.put("cde", 125);
		
		//1.Map集合方法的entrySet() 获取到Entry接口实现类对象,存储Set集合
		Set<Map.Entry<String, Integer>> set = map.entrySet();
		
		//2.遍历Set集合
		Iterator<Map.Entry<String, Integer>> it = set.iterator();
		while(it.hasNext()) {
			//3.取出Set集合中的元素,是Entry接口的实现类对象(键值对的对应关系)
			Map.Entry<String, Integer> entry = it.next();
			//4.Entry接口对象,调用方法getKey(),getValue()
			String key = entry.getKey();
			Integer value = entry.getValue();
			System.out.println(key+"="+value);
		}
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值