黑马程序员——JAVA基础之Map集合

------- android培训java培训、期待与您交流! ----------

Map集合:

该集合存储键值对。一对一对往里存。而且要保证键的唯一性。

和Set很像,其实Set底层就是使用了Map集合。

 

 

Map与Collection:
   Map与Collection在集合框架中属并列存在
   Map存储的是键值对
   Map存储元素使用put方法,Collection使用add方法
   Map集合没有直接取出元素的方法,而是先转成Set集合,在通过迭代获取元素
   Map集合中键要保证唯一性

 

Map集合常用类

   Hashtable:线程安全,速度慢,底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。jdk1.0.效率低。已被HashMap替代。
   HashMap:底层是哈希表数据结构,线程不安全,速度快,允许存放null键,null值,jdk1.2.效率高。
   TreeMap:对键进行排序,排序原理与TreeSet相同。底层是二叉树数据结构。线程不同步。可以用于给map集合中的键进行排序。

 

 

常用方法:

    1.添加。
        put(K key, V value)  将指定的值与此映射中的指定键关联
        putAll(Map<? extends K,? extends V> m)  从指定映射中将所有映射关系复制到此映射中

                    如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。

 

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

/**
 * 
 * Map集合添加的简单演示
 *
 */
public class MapDemo 
{
	public static void main(String[] args)
	{
		Map<String,Integer> m = new HashMap<String,Integer>();
		
		m.put("zhangsan", 19);
		m.put("lisi", 49);//如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
		m.put("wangwu", 19);
		m.put("lisi",20);//put方法会返回被覆盖的值。
		m.put("hanmeimei", null);
		
		System.out.println(m);
	}
}



    2.删除。
        clear()  从此映射中移除所有映射关系

        remove(Object key) 如果存在一个键的映射关系,则将其从此映射中移除  

 

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

/**
 * 
 * Map集合删除的简单演示
 *
 */
public class MapDemo 
{
	public static void main(String[] args)
	{
		Map<String,Integer> m = new HashMap<String,Integer>();
		
		m.put("zhangsan", 19);
		m.put("lisi", 49);//如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
		m.put("wangwu", 19);
		m.put("lisi",20);//put方法会返回被覆盖的值。
		m.put("hanmeimei", null);		
		System.out.println(m);
		
		System.out.println(m.remove("wangwu"));
		
		m.clear();
		System.out.println(m);		
	}
}

 


    3.判断。
        containsValue(Object value)  如果此映射将一个或多个键映射到指定值,则返回 true

        containsKey(Object key)   如果此映射包含指定键的映射关系,则返回 true

        isEmpty()  如果此映射未包含键-值映射关系,则返回 true

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

/**
 * 
 * Map集合判断的简单演示
 *
 */
public class MapDemo 
{
	public static void main(String[] args)
	{
		Map<String,Integer> m = new HashMap<String,Integer>();
		
		m.put("zhangsan", 19);
		m.put("lisi", 49);//如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
		m.put("wangwu", 19);
		m.put("lisi",20);//put方法会返回被覆盖的值。
		m.put("hanmeimei", null);		
		System.out.println(m);
		
		System.out.println(m.containsKey("lisi"));
		System.out.println(m.containsValue(20));
		System.out.println(m.isEmpty());		
	}
}


 


    4.获取。
        get(Object key)  返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回 null
        size()  返回此映射中的键-值映射关系数。
        values()  返回此映射中包含的值的 collection 视图
 
        entrySet()  返回此映射中包含的映射关系的 set 视图。
        keySet()  返回此映射中包含的映射关系的 key 视图。

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

/**
 * 
 * Map集合获取的简单演示
 *
 */
public class MapDemo 
{
	public static void main(String[] args)
	{
		Map<String,Integer> m = new HashMap<String,Integer>();
		
		m.put("zhangsan", 19);
		m.put("lisi", 49);//如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
		m.put("wangwu", 19);
		m.put("lisi",20);//put方法会返回被覆盖的值。
		m.put("hanmeimei", null);		
		System.out.println(m);
		
		//通过get方法返回null的情况可以当作第二种判断方式
		System.out.println(m.get("lisi"));
		System.out.println(m.size());//4
		System.out.println(m.values());	//[19, 20, 19, null]
		System.out.println(m.entrySet());//[wangwu=19, lisi=20, zhangsan=19, hanmeimei=null]
		System.out.println(m.keySet());//[wangwu, lisi, zhangsan, hanmeimei]
	}
}


 

map集合的两种取出方式:
1 . Set<k> keySet:将map中所有的键存入到Set集合。因为set具备迭代器。所有可以迭代方式取出所有的键,在根据get方法。获取每一个键对应的值。
     Map集合的取出原理:将map集合转成set集合。在通过迭代器取出。
2 . Set<Map.Entry<k,v>> entrySet:将map集合中的映射关系存入到了set集合中,而这个关系的数据类型就是:Map.Entry
     Entry其实就是Map中的一个static内部接口。
     定义在内部因为只有有了Map集合,有了键值对,才会有键值的映射关系。关系属于Map集合中的一个内部事物。而且该事物在直接访问Map集合中的元素。

 

 

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

/**
 * 
 * Map集合判断的简单演示
 *
 */
public class MapDemo 
{
	public static void main(String[] args)
	{
		Map<String,Integer> m = new HashMap<String,Integer>();
		
		m.put("zhangsan", 19);
		m.put("wangwu", 19);
		m.put("lisi",20);
		
		System.out.println(m);
		
		//方法1,将Map集合中的映射关系取出,
		Set<Map.Entry<String,Integer>> entrySet = m.entrySet();
		for (Iterator<Map.Entry<String,Integer>> it = entrySet.iterator();it.hasNext(); )
		{
			Map.Entry<String, Integer> me = it.next();
			String Key = me.getKey();
			Integer Value = me.getValue();
			System.out.println(Key+"------"+Value);
		}
		
		//方法2.先获取键的集合
		Set<String> keySet = m.keySet();
		for (Iterator<String> it = keySet.iterator();it.hasNext(); )
		{
			String key = it.next();
			int value = m.get(key);
			
			System.out.println(key+"---"+value);			
		}
	}
}


 

/*
每一个学生都有对应的归属地。
学生Student,地址String。
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。

1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。
3,获取map集合中的元素。
*/

import java.util.*;
class Student implements Comparable<Student>
{
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}	
	public int compareTo(Student s)
	{
		int num = new Integer(this.age).compareTo(new Integer(s.age));

		if(num==0)
			return this.name.compareTo(s.name);
		return num;
	}
	public int hashCode()
	{
		return name.hashCode()+age*34;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Student))
			throw new ClassCastException("类型不匹配");

		Student s = (Student)obj;

		return this.name.equals(s.name) && this.age==s.age;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
	public String toString()
	{
		return name+":"+age;
	}
}
class  MapTest
{
	public static void main(String[] args) 
	{
		HashMap<Student,String> hm = new HashMap<Student,String>();

		hm.put(new Student("lisi1",21),"beijing");
		hm.put(new Student("lisi1",21),"tianjin");
		hm.put(new Student("lisi2",22),"shanghai");
		hm.put(new Student("lisi3",23),"nanjing");
		hm.put(new Student("lisi4",24),"wuhan");
		//第一种取出方式 keySet
		Set<Student> keySet = hm.keySet();
		Iterator<Student> it = keySet.iterator();
		while(it.hasNext())
		{
			Student stu = it.next();
			String addr = hm.get(stu);
			System.out.println(stu+".."+addr);
		}
		//第二种取出方式 entrySet
		Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
		Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();		
		while(iter.hasNext())
		{
			Map.Entry<Student,String> me = iter.next();
			Student stu = me.getKey();
			String addr = me.getValue();
			System.out.println(stu+"........."+addr);
		}
	}
}


 

 

/*
需求:对学生对象的年龄进行升序排序。
因为数据是以键值对形式存在的。所以要使用可以排序的Map集合。TreeMap。
*/
import java.util.*;

class StuNameComparator implements Comparator<Student>
{
	public int compare(Student s1,Student s2)
	{
		int num = s1.getName().compareTo(s2.getName());
		if(num==0)
			return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));

		return num;
	}
}

class Student implements Comparable<Student>
{
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}	
	public int compareTo(Student s)
	{
		int num = new Integer(this.age).compareTo(new Integer(s.age));

		if(num==0)
			return this.name.compareTo(s.name);
		return num;
	}
	public int hashCode()
	{
		return name.hashCode()+age*34;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Student))
			throw new ClassCastException("类型不匹配");

		Student s = (Student)obj;

		return this.name.equals(s.name) && this.age==s.age;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
	public String toString()
	{
		return name+":"+age;
	}
}
class  MapTest2
{
	public static void main(String[] args) 
	{
		TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());

		tm.put(new Student("blisi3",23),"nanjing");
		tm.put(new Student("lisi1",21),"beijing");
		tm.put(new Student("alisi4",24),"wuhan");
		tm.put(new Student("lisi1",21),"tianjin");
		tm.put(new Student("lisi2",22),"shanghai");

		
		Set<Map.Entry<Student,String>> entrySet = tm.entrySet();

		Iterator<Map.Entry<Student,String>> it = entrySet.iterator();

		while(it.hasNext())
		{
			Map.Entry<Student,String> me = it.next();

			Student stu = me.getKey();
			String addr = me.getValue();
			System.out.println(stu+":::"+addr);
		}
	}
}


 

 

/*
练习:
"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。

希望打印结果:a(1)c(2).....

通过结果发现,每一个字母都有对应的次数。说明字母和次数之间都有映射关系。
注意了,当发现有映射关系时,可以选择map集合。因为map集合中存放就是映射关系。

当数据之间存在这映射关系时,就要先想map集合。

思路:
1,将字符串转换成字符数组。因为要对每一个字母进行操作。
2,定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合。
3,遍历字符数组。
   将每一个字母作为键去查map集合。
   如果返回null,将该字母和1存入到map集合中。
   如果返回不是null,说明该字母在map集合已经存在并有对应次数。
   那么就获取该次数并进行自增。,然后将该字母和自增后的次数存入到map集合中。覆盖调用原理键所对应的值。
4,将map集合中的数据变成指定的字符串形式返回。
*/
import java.util.*;
class  MapTest3
{
	public static void main(String[] args) 
	{
		String s= charCount("ak+abAf1c,dCkaAbc-defa");
		System.out.println(s);
	}	
	public static String charCount(String str)
	{
		char[] chs = str.toCharArray();
		TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();		
		int count = 0;
		for(int x=0; x<chs.length; x++)
		{
			if(!(chs[x]>='a' && chs[x]<='z' || chs[x]>='A' && chs[x]<='Z'))
				continue;
			Integer value = tm.get(chs[x]);			
			if(value!=null)
				count = value;
			count++;
			tm.put(chs[x],count);//直接往集合中存储字符和数字,为什么可以,因为自动装箱。
			count = 0;
		}
		StringBuilder sb = new StringBuilder();
		Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
		Iterator<Map.Entry<Character,Integer>>  it = entrySet.iterator();
		while(it.hasNext())
		{
			Map.Entry<Character,Integer> me = it.next();
			Character ch = me.getKey();
			Integer value = me.getValue();
			sb.append(ch+"("+value+")");
		}
		return sb.toString();
	 }
}

 

 

 

map扩展知识:

               map集合被使用是因为具备映射关系。


 

/*
"yureban"   Student("01" "zhangsan");
"yureban" Student("02" "lisi");
"jiuyeban" "01" "wangwu";
"jiuyeban" "02" "zhaoliu";

一个学校有多个教室。每一个教室都有名称。
*/
import java.util.*;

class Student
{
	private String id;
	private String name;
	Student(String id,String name)
	{
		this.id = id;
		this.name = name;
	}
	public String toString()
	{
		return id+":::"+name;
	}
}
class  MapDemo3
{

	public static void demo()
	{
		HashMap<String,List<Student>> czbk = new HashMap<String,List<Student>>();

		List<Student> reyu = new ArrayList<Student>();
		List<Student> jiuye = new ArrayList<Student>();

		czbk.put("yureban",reyu);
		czbk.put("jiuyeban",jiuye);

		reyu.add(new Student("01","zhagnsa"));
		reyu.add(new Student("04","wangwu"));
		jiuye.add(new Student("01","zhouqi"));
		jiuye.add(new Student("02","zhaoli"));


		Iterator<String> it = czbk.keySet().iterator();

		while(it.hasNext())
		{
			String roomName = it.next();
			List<Student> room = czbk.get(roomName);
			
			System.out.println(roomName);
			getInfos(room);
		}	
	}
	public static void getInfos(List<Student> list)
	{
		Iterator<Student> it = list.iterator();
		while(it.hasNext())
		{
			Student s = it.next();
			System.out.println(s);
		}
	}
	public static void main(String[] args) 
	{
		 demo();
		
	}
	public static void getStudentInfo(HashMap<String,String> roomMap)
	{
		Iterator<String> it = roomMap.keySet().iterator();

		while(it.hasNext())
		{
			String id = it.next();
			String name = roomMap.get(id);
			System.out.println(id+":"+name);
		}
	}
}


 

 

 

------- android培训java培训、期待与您交流! ----------

 

原文地址:https://www.cnblogs.com/runwind/p/4212185.html