Map的两种遍历方法

Map

方法一:Map集合的遍历之 键找值

键找值思路:

  • 通过map.keySet()方法,获取所有键(key)的集合
  • 遍历键的集合,获取到每一个键(key)
  • 根据键找值map.get(key)
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("a", "张三");
		map.put("b", "李四");
		map.put("c", "王五");
		map.put("d", "赵六");

		// 1.通过map.keySet()方法,获取所有键(key)的集合
		Set<String> keySet = map.keySet();
		Iterator<String> it = keySet.iterator();
		while (it.hasNext()) {
			// 2.迭代器遍历键的集合,获取到每一个键(key)
			String key = it.next();
			// 3.根据 键 找 值 map.get(key);
			String value = map.get(key);
			System.out.println(key + "的值为:" + value);
		}

		// 简化如下:
		/*Set<String> set = map.keySet();
		for (String key : set) {
			System.out.println(key + "的值为:" + map.get(key));
		}*/

	}

方法二:Map集合的遍历之 键值对对象找值

键值对对象找值思路:

  • 通过map.entrySet()方法获取键值对对象集合Set<Entry<K,V>>
  • 遍历键值对对象获取键(key)和值(value)
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("a", "张三");
		map.put("b", "李四");
		map.put("c", "王五");
		map.put("d", "赵六");

		// Map.Entry接口是Map接口内部的接口,在HashMap中有内部类Entry实现了Map.Entry接口
		// 1.通过map.entrySet()方法获取键值对 对象集合Set<Entry<,V>
		Set<Entry<String, String>> entryset = map.entrySet();
		// 2.遍历键值对 对象获取键(key)和值(value)
		Iterator<Entry<String, String>> it = entryset.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key + "的值为:" + value);
		}

		// 简化如下:
		/*for (Entry<String, String> en : map.entrySet()) {
			System.out.println(en.getKey() + "的值为:" + en.getValue());
		}*/

	}

HashMap

如何保证键的唯一?

HashMap当键(key)是对象(Student)时,如果对象(Student)没有重写hashCode和equals方法,则不会去重,即键值可能会有重复。如果需要去重,则需要重写对象的hashcode和equals方法。

	public static void main(String[] args) {
		// LinkedHashMap是HashMap的子类。
		//特点:底层是链表,所以可实现怎么存怎么取。
		LinkedHashMap<String, String> lhm = new LinkedHashMap<>();
		lhm.put("a", "张三");
		lhm.put("b", "李四");
		lhm.put("c", "王五");
		lhm.put("d", "赵六");
		
		for (String key : lhm.keySet()) {
			System.out.println(key + "的值为:" + lhm.get(key));
		}
	}

TreeMap(存键的底层是二叉树):

如何保证键的唯一?

TreeMap底层是二叉树,所以类比TreeSet,保证键唯一有两种方式:

  1. 对象继承Comparator接口,重写compareTo方法
  2. 在TreeMap中传入Comparetor对象,重写compareTo方法

HashMap<K,V>与Hashtable<K,V>的区别(面试题)

共同点:

  • 底层都是hash算法,都是双列集合。

区别:

  • HashMap线程不安全,效率高,JDK1.2版本。
  • Hashtable是线程安全的,效率低,JDLK1.0版本。
  • Hashtable不可以存储null键和null值。
  • HashMap可以存储null键和null值。
     

转载请注明出处:BestEternity亲笔。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值