Java_18 Map与Set集合---③Map(集合)

一、Map接口的概述

通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它们存储数据的形式不同:

A:Collection中的集合,元素是孤立存在的(理解为单身),向集合中存储元素采用一个个元素的方式存储
B:Map中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键可以找对所对应的值。
C:Collection中的集合称为单列集合,Map中的集合称为双列集合。
需要注意的是,Map中的集合不能包含重复的键,值可以重复;每个键只能对应一个值。

如:实现学号和姓名这样有对应关系的数据存储
Map:将键映射到值的对象,一个映射不能包含重复的键,每个键最多只能映射到一个值。

二、Map的功能概述

A:映射功能:

 V put(K key, V value) :以键=值的方式存入Map集合。将key映射到value,如果key存在,则覆盖value,并将原来的value返回;若key不存在,则返回null

B:获取功能:

 V get(Object key):根据键获取值
int size():返回Map中键值对的个数

C:判断功能:

boolean containsKey(Object key):判断Map集合中是否包含键为key的键值对
boolean containsValue(Object value):判断Map集合中是否包含值为value键值对
boolean isEmpty():判断Map集合中是否没有任何键值对 

D:删除功能:

  void clear():清空Map集合中所有的键值对
  V remove(Object key):根据键值删除Map中键值对

E:遍历功能:

  Set<Map.Entry<K,V>> entrySet():将每个键值对封装到一个个Entry对象中,再把所有Entry的对象封装到Set集合中返回

Set keySet() :将Map中所有的键装到Set集合中返回
Collection values():返回集合中所有的value的值的集合

import java.util.HashMap;
import java.util.Map;


public class MapDemo2 {
	public static void main(String[] args) {
		//创建Map对象
		Map<String,String> map = new HashMap<String,String>();
		
		//V put(K key, V value) :就是将key映射到value,如果key存在,则覆盖value,并将原来的value返回
		System.out.println(map.put("ITCAST001", "张三"));
		System.out.println(map.put("ITCAST002", "李四"));
		System.out.println(map.put("ITCAST001", "王五"));
		/*
			返回结果:
				null
				null
				张三
				{ITCAST002=李四,ITCAST001=张三}
		*/
		
		//void clear() : 清空所有的对应关系  
		//map.clear();
		
		//V remove(Object key) :根据指定的key删除对应关系,并返回key所对应的值,如果没有删除成功则返回null
		//System.out.println(map.remove("ITCAST005"));
		
		//boolean containsKey(Object key) : 判断指定key是否存在
		//System.out.println(map.containsKey("ITCAST003"));
		
		//boolean containsValue(Object value):判断指定的value是否存在
		//System.out.println(map.containsValue("王五"));
		
		//boolean isEmpty() : 判断是否有对应关系
		//System.out.println(map.isEmpty());
		
		//int size() : 返回对应关系的个数
		//System.out.println(map.size());
		
		//V get(Object key) : 根据指定的key返回对应的value
		System.out.println(map.get("ITCAST002"));
		
		System.out.println(map);
	}
}

KeySet和values测试

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
 * 	Set<K> keySet()  
 * 	Collection<V> values() 
 */
public class MapDemo3 {
	public static void main(String[] args) {
		//创建Map对象
		Map<String,String> map = new HashMap<String,String>();
		//添加映射关系
		map.put("ITCAST001", "张三");
		map.put("ITCAST002", "李四");
		map.put("ITCAST005", "李四");
		
		//Set<K> keySet() : 以Set的形式获返回所有的key
		Set<String> keys = map.keySet();
		/*
			为什么keySet方法的返回类型是Set
				因为key值不允许重复,而Set的集合特点是不允许重复
		*/
		for (String key : keys) {
			System.out.println(key);
		}
		System.out.println("-----------");
		
		//Collection<V> values() :
		/*
			为什么values方法的返回类型是Collection
				因为value值是允许重复的,而collection是允许重复的集合
			那为什么返回类型不是list
				因为在jdk的API文档中,values方法返回类型是Collection,会创建一个内部类Values对象(values = new Values() ),
				而内部类Values()方法继承了AbstractCollection,
				而AbstractCollection实现了Collection接口,
				因此values方法返回类型不是list,且没有索引。
		*/
		Collection<String> values = map.values();
		for (String value : values) {
			System.out.println(value);
		}
	}
}

三、Map的第一种遍历方式

1、利用keySet()方法遍历

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
 * 	Map的第一种遍历方式:
 * 			首先召集所有的丈夫
 * 			遍历所有的丈夫
 * 			获取每一个丈夫
 * 			让每一个丈夫去找他自己的媳妇
 */
public class MapDemo4 {
	public static void main(String[] args) {
		//创建Map对象
		Map<String,String> map = new HashMap<String,String>();
		//添加映射关系
		map.put("谢", "张");
		map.put("陈", "钟");
		map.put("李", "王");
		//遍历Map对象
		
		//首先召集所有的丈夫
		Set<String> keys = map.keySet();
		//遍历所有的丈夫
		for (String key : keys) {
			//让每个丈夫去找他自己的媳妇就可以了
			String value = map.get(key);
			System.out.println("丈夫:" + key + "---" + "媳妇:" + value);
		}
		
	}
}

2、利用entrySet()方法遍历

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
 * 	Map的第二种遍历方式:
 * 		通过结婚证对象来获取丈夫和媳妇
 * 
 *  class 结婚证<K,V> {
 *  	K 丈夫;
 *  	V 媳妇;
 *  
 *  	public 结婚证(K 丈夫,V 媳妇) {
 *  		this.丈夫 = 丈夫;
 *  		this.媳妇 = 媳妇;
 *  	}
 *  
 *  
 *  	public K get丈夫() {
 *  		return 丈夫;
 *  	}
 *  
 *  	public V get媳妇() {
 *  		return 媳妇;
 *  	}
 *  }
 *  
 *  
 *  class Entry<K,V> {
 *  	K key;
 *  	V value;
 *  
 *  	public Entry(K key,V value) {
 *  		this.key = key;
 *  		this.value = value;
 *  	}
 *  
 *  
 *  	public K getKey() {
 *  		return key;
 *  	}
 *  
 *  	public V getValue() {
 *  		return value;
 *  	}
 *  }
 *  
 *  Set<Map.Entry<K,V>> entrySet()  
 * 
 */
public class MapDemo5 {
	public static void main(String[] args) {
		//创建Map对象
		Map<String,String> map = new HashMap<String,String>();
		//添加映射关系
		map.put("尹志平", "小龙女");
		map.put("令狐冲", "东方菇凉");
		map.put("玄慈", "叶二娘");
		//获取所有的结婚证对象
		Set<Map.Entry<String,String>> entrys = map.entrySet();
		//遍历包含了结婚证对象的集合
		for (Map.Entry<String, String> entry : entrys) {
			//获取每个单独的结婚证对象
			//通过结婚证对象获取丈夫和媳妇
			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println("丈夫:" + key + "---" + "媳妇:" + value);
		}
		
	}
}

案例1:以key为学号字符串,value为学生姓名存入HashMap集合,分别以两种方式遍历集合

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
 * 
 * 使用HashMap存储数据并遍历(字符串作为key)
 * 
 */
public class HashMapDemo {
	public static void main(String[] args) {
		//创建Map对象
		HashMap<String,String> hm = new HashMap<String,String>();
		//添加映射关系
		hm.put("ITCAST001", "张三");
		hm.put("ITCAST002", "李四");
		hm.put("ITCAST003", "王五");
		hm.put("ITCAST003", "赵六");
		//遍历Map对象
		
		//方式1 获取所有的key,通过key来获取value
		Set<String> keys = hm.keySet();
		for (String key : keys) {
			String value = hm.get(key);
			System.out.println(key + "=" + value);
		}
		
		System.out.println("------------------");
		
		//方式2:获取所有的结婚证对象,然后通过结婚证对象获取丈夫和媳妇
		Set<Map.Entry<String, String>> entrys = hm.entrySet();
		for (Map.Entry<String, String> entry : entrys) {
			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key + "=" + value);
		}
	}
}

案例2: 定义一个学生类,学生类中有name和age两个属性,创建三个学生对象,分别对name和age赋值,然后以key为学生对象,value为学生的学号的方式存入HashMap集合,利用两种方式遍历这个Map

HashMapDemo2 .java

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/*
 * 
 * 使用HashMap存储数据并遍历(自定义对象作为key)
 * 
 */
public class HashMapDemo2 {
	public static void main(String[] args) {
		//创建Map对象
		HashMap<Student,String> hm = new HashMap<Student,String>();
		//创建key对象
		Student s = new Student("zhangsan",18);
		Student s2 = new Student("lisi",20);
		Student s3 = new Student("lisi",20);
		
		//添加映射关系
		hm.put(s, "ITCAST001");
		hm.put(s2, "ITCAST002");
		hm.put(s3, "ITCAST002");
		
		//遍历Map对象
		//方式1: 获取所有的key,通过key来获取value
		Set<Student> keys = hm.keySet();
		for (Student key : keys) {
			String value = hm.get(key);
			System.out.println(key + "=" + value);
		}
		System.out.println("-----");
		
		//方式2:获取所有结婚证对象,通过结婚证对象获取丈夫和媳妇
		Set<Map.Entry<Student, String>> entrys = hm.entrySet();
		for (Entry<Student, String> entry : entrys) {
			Student key = entry.getKey();
			String value = entry.getValue();
			
			System.out.println(key + "=" + value);
		}
		
	}
}

Student.java(重写hashCode、equals方法,同Set集合一致)

public class Person {
	String name;
	int age;
	
	public Person(String name,int age) {
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

猜你喜欢

转载自blog.csdn.net/weixin_43801116/article/details/107579390
今日推荐