Java常用对象API——Map集合

java.util

接口 Map<K,V>

public interface Map<K,V>
将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。

Map集合中存储的就是键值对,且必须保证键的唯一性。
与collction的对比:
Map:一次添加一对元素。Collection 一次添加一个元素。
Map也称为双列集合,Collection集合称为单列集合。
注意,Map<K,V>中K,V只能是对象引用类型,所以里面要写对象包装类。

常用方法:

1,添加。
value(这指的是返回值) put(key,value):返回前一个和key关联的值(旧值),如果没有返回null.
2,删除。
void clear():清空map集合。
value remove(key):根据指定的key删除这个键值对。
3,判断。
boolean containsKey(key):
boolean containsValue(value):
boolean isEmpty();
4,获取。
value get(key):通过键获取值,如果没有该键返回null。
当然可以通过返回null,来判断是否包含指定键。
int size(): 获取键值对的个数。

演示

public class MapDemo {

	public static void main(String[] args) {
		
		Map<Integer,String> map = new HashMap<Integer,String>();
		method(map);
	}
	public static void method(Map<Integer,String> map){//学号和姓名
		
		
		// 添加元素。
		System.out.println(map.put(8, "wangcai"));//返回null
		System.out.println(map.put(8, "xiaoqiang"));//wangcai 存相同键,值会覆盖。
		map.put(2,"zhangsan");
		map.put(7,"zhaoliu");
		//删除。		
		System.out.println("remove:"+map.remove(2));
		
		//判断。
		System.out.println("containskey:"+map.containsKey(7));
		
		//获取。 
		System.out.println("get:"+map.get(6));
		
		System.out.println(map);
	}
	
}

在这里插入图片描述

重点方法keySet演示:

Map是没有迭代器可以直接使用的,通过keySet方法获取map中所有的键所在的Set集合,再通过Set的迭代器获取到每一个键。

public class MapDemo {

	public static void main(String[] args) {
		
		Map<Integer,String> map = new HashMap<Integer,String>();
		method(map);
	}
	public static void method_2(Map<Integer,String> map){
		
		map.put(8,"zhaoliu");
		map.put(2,"zhaoliu");
		map.put(7,"xiaoqiang");
		map.put(6,"wangcai");
		//要取出map中的所有元素,但是map是没有迭代器可以直接使用的。
		//原理,通过keySet方法获取map中所有的键所在的Set集合,再通过Set的迭代器获取到每一个键
		//再对每一个键通过map集合的get方法获取其对应的值即可。
		
		Set<Integer> keySet = map.keySet();
		Iterator<Integer> it = keySet.iterator();
		
		while(it.hasNext()){
			Integer key = it.next();
			String value = map.get(key);
			System.out.println(key+":"+value);
			
		}
	}

运行结果:
在这里插入图片描述

原理图解:在这里插入图片描述

重点方法entrySet演示:

public class MapDemo {

	public static void main(String[] args) {
		
		Map<Integer,String> map = new HashMap<Integer,String>();
		method_2(map);
	}
	
	public static void method_2(Map<Integer,String> map){
		
		map.put(8,"zhaoliu");
		map.put(2,"zhaoliu");
		map.put(7,"xiaoqiang");
		map.put(6,"wangcai");
		/*
		 * 通过Map转成set就可以迭代。
		 * 找到了另一个方法。entrySet。
		 * 该方法将键和值的映射关系作为对象存储到了Set集合中,而这个映射关系的类型就是Map.Entry类型(结婚证)
		 * 
		 * 
		 */
		
		Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
		
		Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
		
		while(it.hasNext()){
			Map.Entry<Integer, String> me = it.next();
			Integer key = me.getKey();
			String value = me.getValue();
			System.out.println(key+"::::"+value);
			
		}
	}
	

运行结果:
在这里插入图片描述

原理图解:
在这里插入图片描述

values方法

这个方法可以只获取值

		//.....................
		map.put(8,"zhaoliu");
		map.put(2,"zhaoliu");
		map.put(7,"xiaoqiang");
		map.put(6,"wangcai");
		
		
		Collection<String> values = map.values();
		
		Iterator<String> it2 = values.iterator();
		while(it2.hasNext()){
			System.out.println(it2.next());
		}

运行结果:
在这里插入图片描述

Map常用的子类:

|–Hashtable :内部结构是哈希表,是同步的。不允许null作为键,null作为值。
…|–Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
|–HashMap : 内部结构是哈希表,不是同步的。允许null作为键,null作为值。
|–TreeMap : 内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。

HashMap演示:

	public static void main(String[] args) {

		
		/*
		 * 将学生对象和学生的归属地通过键与值存储到map集合中。
		 * 
		 */
		
		HashMap<Student,String> hm = new HashMap<Student,String>();

		
		hm.put(new Student("lisi",38),"北京");
		hm.put(new Student("zhaoliu",24),"上海");
		hm.put(new Student("xiaoqiang",31),"沈阳");
		hm.put(new Student("wangcai",28),"大连");
		hm.put(new Student("zhaoliu",24),"铁岭");
		
//		Set<Student> keySet = hm.keySet();		
//		Iterator<Student> it = keySet.iterator();
		
		Iterator<Student> it = hm.keySet().iterator();
		
		while(it.hasNext()){
			Student key = it.next();
			String value = hm.get(key);
			System.out.println(key.getName()+":"+key.getAge()+"---"+value);
		}
		
		
	}

}

运行结果:注意,存在了覆盖情况。(参考HashSet)
在这里插入图片描述

TreeMap演示

演示了排序功能。注意比较器的用法,参考上一篇文章。

public class TreeMapDemo {

	
	public static void main(String[] args) {

		TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName()); //传入比较器,通过姓名排序
		
		tm.put(new Student("lisi",38),"北京");
		tm.put(new Student("zhaoliu",24),"上海");
		tm.put(new Student("xiaoqiang",31),"沈阳");
		tm.put(new Student("wangcai",28),"大连");
		tm.put(new Student("zhaoliu",24),"铁岭");
		
		
		Iterator<Map.Entry<Student, String>> it = tm.entrySet().iterator();
		
		while(it.hasNext()){
			Map.Entry<Student,String> me = it.next();
			Student key = me.getKey();
			String value = me.getValue();
			
			System.out.println(key.getName()+":"+key.getAge()+"---"+value);
		}
		
	}

}

这是通过姓名排序的结果
在这里插入图片描述

LinkedHashMap

特点:有序存取
例子:

public class LinkedHashMapDemo {

	
	public static void main(String[] args) {
		
		File f= null;
		HashMap<Integer,String> hm = new LinkedHashMap<Integer,String>(); //有序存取
		hm.put(7, "zhouqi");
		hm.put(3, "zhangsan");
		hm.put(1, "qianyi");
		hm.put(5, "wangwu");
		
		Iterator<Map.Entry<Integer,String>> it = hm.entrySet().iterator();
		
		while(it.hasNext()){
			Map.Entry<Integer,String> me = it.next();
			
			Integer key = me.getKey();
			String value = me.getValue();
			
			System.out.println(key+":"+value);
		}
	}

}

取出来的数据和存入时的顺序是一样的
在这里插入图片描述

Map集合练习——获取字符串中每一个字母出现的次数

练习:

  • “fdgavcbsacdfs” 获取该字符串中,每一个字母出现的次数。
  • 要求打印结果是:a(2)b(1)…;

思路

  • 对于结果的分析发现,字母和次数之间存在着映射关系。而且这种关系很多。
  • 很多就需要存储,能存储映射关系的容器有数组和Map集合。
  • 关系一方式有序编号吗?没有!
  • 那就是使用Map集合。 又发现可以保证唯一性的一方具备着顺序如 a b c …
  • 所以可以使用TreeMap集合。
  • 这个集合最终应该存储的是字母和次数的对应关系。
  • 1,因为操作的是字符串中的字母,所以先将字符串变成字符数组。
  • 2,遍历字符数组,用每一个字母作为键去查Map集合这个表。
  • 如果该字母键不存在,就将该字母作为键 ,1作为值存储到map集合中。
  • 如果该字母键存在,就将该字母键对应值取出并+1,在将该字母和+1后的值存储到map集合中,
  • 键相同值会覆盖。这样就记录住了该字母的次数.
  • 3,遍历结束,map集合就记录所有字母的出现的次数。

代码:

public class MapTest {

	
	public static void main(String[] args) {

		
		String str = "fdg+avAdc  bs5dDa9c-dfs";
		
		String s = getCharCount(str);//获取字符的个数(自己实现)
		
		System.out.println(s);
		
	}

	public static String getCharCount(String str) {
		
		
		//将字符串变成字符数组 
		char[] chs = str.toCharArray(); 
		
		//定义map集合表。
		Map<Character,Integer> map = new TreeMap<Character,Integer>();
		
		for (int i = 0; i < chs.length; i++) {
			
			if(!(chs[i]>='a' && chs[i]<='z' || chs[i]>='A' && chs[i]<='Z'))
//			if(!(Character.toLowerCase(chs[i])>='a' && Character.toLowerCase(chs[i])<='z'))
				continue;
			
			//将数组中的字母作为键去查map表,返回其值			
			Integer value = map.get(chs[i]);
			
			int count = 1;
			
			//判断值是否为null.
			if(value!=null){
				count = value+1;
			}
//			count++;
			map.put(chs[i], count);
		
		}
		
		
		
		
		
		return mapToString(map);//自己实现
	}

	private static String mapToString(Map<Character, Integer> map) {  //传入一个Map集合,返回一个字符串
		
		StringBuilder sb = new StringBuilder(); //字符串缓冲区
		
		Iterator<Character> it = map.keySet().iterator(); //获得一个Map中所有键所在的Set集合,再通过Set创建一个迭代器,以此来获得每一个键
		
		while(it.hasNext()){
			Character key = it.next();  //获得键
			Integer value = map.get(key); //再通过键获得值
			
			sb.append(key+"("+value+")"); //用append方法连成字符串
		}
		
		return sb.toString(); //再用字符串缓冲区的方法一次性转化为字符串
	}

}

运行结果:在这里插入图片描述

Map查表法

Map在有映射关系(甚至特别多)时,可以优先考虑。 在查表法中的应用较为多见。

public class MapTest2 {


	public static void main(String[] args) {

	
		
		String week = getWeek(1);
		System.out.println(week);
		
		System.out.println(getWeekByMap(week));
	}
	public static String getWeekByMap(String week){
		
		Map<String,String> map = new HashMap<String,String>();
		
		map.put("星期一","Mon");
		map.put("星期二","Tus");
		map.put("星期三","Wes");
		map.put("星期日","Sun");
		map.put("星期天","Sun");
		
		return map.get(week);
	}
	
	
	public static String getWeek(int week){
		
		if(week<1 || week>7)
			throw new RuntimeException("没有对应的星期,请您重新输入");
		
		String[] weeks = {"","星期一","星期二"};
		
		return weeks[week];
	}

}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/z714405489/article/details/83032731