从零双排java之Map

Map是一种 Key-Value(键值对)形式的集合,又称双列集合

Key的值是 唯一的 一个Map集合中 Key 可以允许有一个是null   

HashMap和HashSet 之间有没有关系    

实际上HashSet的去重功能是通过向一个Map集合的Key存储数据来实现的

Map集合中不管是去重还是排序 指的都是Key这一列


一些常用的方法:

// 判断包含key
		boolean containsKey = map.containsKey("彭中");
// 判断包含Value
		boolean containsValue = map.containsValue(13);
// 获Map中所有Key的集合
		Set<String> keySet = map.keySet();
// 获取map中所有Value 的collection集合
		Collection<Integer> values = map.values();

// 删除 根据key 删除这个键值对 返回值是删除的value
		Integer(这里的数据类型是被Value的数据类型) remove = map.remove("彭前");
// 清空
		map.clear();

// Entry接口 是Map接口中的内部接口
		// Entry中保存的是 键值对对象
		// 相当于把map 中的Key 和VAlue封装成了一个对象
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		Integer put = map.put("彭前", 13);
		Integer put2 = map.put("彭后", 12);
		Integer put3 = map.put("彭左", 11);
		Integer put4 = map.put("彭右", 15);
		// 利用entrySet遍历集合 一个用迭代器 一个用fore
		Set<Entry<String, Integer>> entrySet = map.entrySet();
		Iterator<Entry<String, Integer>> iterator = entrySet.iterator();
		while (iterator.hasNext()) {
			// 获取迭代器中的 Entry对象
			Entry<String, Integer> next = iterator.next();
			// 从对象中获取Key和Value
			System.out.println(next.getKey());
			System.out.println(next.getValue());
		}
		for (Entry<String, Integer> entry : entrySet) {
			System.out.println(entry);
		}





猜你喜欢

转载自blog.csdn.net/jsymax/article/details/80443282