_046_Map集合

===================================

如果实现了Map的集合类,具备的特点:存储的数据都是以键值对的形式存在的,键不可重复,值可以重复
因为Map是接口,所以要用它的实现类 HashMap  TreeMap Hashtable

HashMap和HashSet一样,不能有重复元素,详情看Set系列

TreeMap和TreeSet一样,不能有重复元素,会自然排序,详情看Set系列

Map的方法

V    put(K key, V value) 
          将指定的值与此映射中的指定键关联(可选操作)
           当存在映射关系的时候,就是一个键先存一个数值,再存一个数值,那么put方法就会返回之前的存的数值,并把现有的数值替换成再存进来的数值

HashMap的方法和Map差不多

下面是HashMap的方法综合

public class Test2 
{
	public static void main(String[] xxx)
	{
		Map<String, String> map1 = new HashMap<String, String>();
		Map<String,String>map2=new HashMap<String,String>();
		 
		//存入元素
		map1.put("abw", "123");
		map2.put("qwe", "哈哈哈");
		
		//如果是相同的键返回的是以前的键值
		System.out.println(map1.put("abw", "1234"));
		System.out.println("集合的元素:" + map1);
		
		 //把map2的元素放到map1的后面
		 map1.putAll(map2);
		 System.out.println(map1);

		//删除,并返回键值
		 System.out.println(map1.remove("abw"));
	
		//清空map2中的所有元素
		map2.clear();
		
		map1.put("abw", "1234");
		map1.put("qwe", "哈哈哈");
		
		//获取键值对的个数
		System.out.println(map1.size());
		
		//判断是否有对应的键和对应的值
		 System.out.println(map1.containsKey("abw"));
		 System.out.println(map1.containsValue("1234"));

		 //判断map是否是空键值对
		 System.out.println(map1.isEmpty());
	}
}

Map的遍历

public class Test2
{
	public static void main(String[] xxx)
	{
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("abw", "123");
		map1.put("qwe", "哈哈哈");

		// 使用keySet遍历元素,先遍历所有key,再用get方法取得值
		 Set<String> set1 = map1.keySet(); // 获取Key的Set集合
		 Iterator<String> iterator = set1.iterator(); // 然后把set集合转换到迭代器遍历出来
		 while (iterator.hasNext())
		 {
		 String value = iterator.next();
		 System.out.println("键:" + value + " 值:" + map1.get(value)); //再用get(遍历出的key)来获取值
		 }

		 System.out.println("===================");
		 
		// 获取到所有的值,但获取不到键
		 Collection<String> collection1 = map1.values();
		 Iterator<String> iterator1 = collection1.iterator();
		 while (iterator1.hasNext())
		 {
		 String string = iterator1.next();
		 System.out.println(string);
		 }

		 System.out.println("===================");
		 
		//利用entrySet直接获取key和value
		Set<Map.Entry<String, String>> set2 = map1.entrySet();
		Iterator<Map.Entry<String, String>> iterator2 = set2.iterator();
		while (iterator2.hasNext())
		{
			Map.Entry<String, String> entry1 = iterator2.next();
			System.out.println("键" + entry1.getKey() + "值" + entry1.getValue());
		}
	}
}

猜你喜欢

转载自blog.csdn.net/yzj17025693/article/details/82762326