Map集合遍历(HashMap,LinkedHashMap,TreeMap)

Map集合的遍历方式
方式1 :根据键找值、获取所有键的值、遍历键的集合,获取每一个键、根据键找值

方式2 ;根据键值对象找键和值、获取所有的键值对象、遍历键值对象的集合,获取到每一个键值对对象、根据键值对象找键值。
方式1

Map<String, String> map = new HashMap<String, String>();

		// 创建元素并添加到集合
		map.put("李白", "王昭君");
		map.put("孙策", "大桥");
		map.put("周瑜", "小乔");
		map.put("猴子", "露娜");

		// 遍历
		// 获取所有的键
		Set<String> set = map.keySet();
		// 遍历键的集合,获取得到每一个键
		for (String key : set) {
			// 根据键去找值
			String value = map.get(key);
			System.out.println(key + "---" + value);
		}

方式2

public static void main(String[] args) {
		// 创建集合对象
		Map<String, String> map = new HashMap<String, String>();

		// 创建元素并添加到集合
		map.put("李白", "王昭君");
		map.put("孙策", "大桥");
		map.put("周瑜", "小乔");
		map.put("猴子", "露娜");
		
		// 获取所有键值对对象的集合
		Set<Map.Entry<String, String>> set = map.entrySet();
		// 遍历键值对对象的集合,得到每一个键值对对象
		for (Map.Entry<String, String> me : set) {
			// 根据键值对对象获取键和值
			String key = me.getKey();
			String value = me.getValue();
			System.out.println(key + "---" + value);
		}

HashMap:是基于哈希表的Map接口实现。 哈希表的作用是用来保证键的唯一性的

看一下代码保证键的唯一性。

public static void main(String[] args) {
		// 创建集合对象
		HashMap<String, String> hm = new HashMap<String, String>();

		// 创建元素并添加元素
		
		hm.put("it001", "赵云");
		hm.put("it003", "曹操");
		hm.put("it004", "张飞");
		hm.put("it005", "火舞");
		hm.put("it002", "李白"); 
		hm.put("it001", "廉颇");

		// 遍历
		Set<String> set = hm.keySet();
		for (String key : set) {
			String value = hm.get(key);
			System.out.println(key + "---" + value);
		}
	}

LinkedHashMap:

  • 是Map接口的哈希表和链接列表实现,具有可预知的迭代顺序。
  • 由哈希表保证键的唯一性
  • 由链表保证键盘的有序(存储和取出的顺序一致)

实现代码

public static void main(String[] args) {
		// 创建集合对象
		LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();

		// 创建并添加元素
		hm.put("it001", "赵云");
		hm.put("it003", "曹操");
		hm.put("it004", "张飞");
		hm.put("it005", "火舞");
		hm.put("it002", "李白"); 
		hm.put("it001", "廉颇");

		// 遍历
		Set<String> set = hm.keySet();
		for (String key : set) {
			String value = hm.get(key);
			System.out.println(key + "---" + value);
		}
	}

TreeMap:是基于红黑树的Map接口的实现。

public static void main(String[] args) {
// 创建集合对象
TreeMap<String, String> tm = new TreeMap<String, String>();

	// 创建元素并添加元素
	hm.put("it001", "赵云");
	hm.put("it003", "曹操");
	hm.put("it004", "张飞");
	hm.put("it005", "火舞");
	hm.put("it002", "李白"); 
	hm.put("it001", "廉颇");

	// 遍历集合
	Set<String> set = tm.keySet();
	for (String key : set) {
		String value = tm.get(key);
		System.out.println(key + "---" + value);
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值