Map接口及其常用方法

Map集合基于(key)和(value)的映射每个键只能映射一个值,也就是说key不可以重复(当然喽,重复的话就按最后一个为准)。键和值都可以是任何引用数据类型的值;且一对键值的存放是无序的。
Map常用的实现类有HashMap、LinkedHashMap、Properties。

这里以HashMap实现类为例演示Map接口方法:

package gather;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;//引包

public class Test{
	public static void main(String[] args) {
		Map<String,Integer> scores = new HashMap<String,Integer>();
		//<String,Integer>称为泛型,其中String用于限定key的数据类型,Integer用于限定value的数据类型
		
		//1、put(K key, V value)向Map集合中添加数据
		scores.put("张三",100);
		scores.put("李四",80);
		scores.put("孙七",90);
		scores.put("周八",50);
		scores.put("周八",60);//重复的就以最后一次为准

		//2、get(Object key)返回指定键所映射的值,没有该键对应的值则返回null
		System.out.println(scores.get("周八"));//60
		System.out.println(scores.get("刘一"));//null

		//3、size()用于返回Map集合中的数据个数
		int size = scores.size();
		System.out.println(size);//4
		
		//4、isEmpty()用于判断Map集合中是否含有数据,如果没有返回true,有则返回false
		boolean flag = scores.isEmpty();
		System.out.println(flag);//false

		//5、remove(Object key)删除Map集合中键为key的数据,并返回其所对应的value值
		System.out.println(scores.remove("周八"));//60
		
		//6、values()用于返回Map集合中所有键对应的值
		System.out.println(scores.values());//[100, 80, 90](不一定是这个顺序)
		
		//7、replace(String key, Integer value)
		//replace(String key, Integer oldValue, Integer newValue)
		//两者都是替换键所对应的值
		scores.replace("张三", 100, 99);
		scores.replace("李四",81);
		System.out.println(scores.values());//[99, 81, 90]

		//8、containsKey(Object key)用于判断集合中是否含有指定键,有则返回true,没有返回false
		//containsValue(Object value)用于判断集合中是否含有指定值,有则返回true,没有返回false
		boolean flag = scores.containsKey("李四");
		System.out.println(flag);//true
		flag = scores.containsValue(100);
		System.out.println(flag);//false
		
		//9、keySet()返回Map集合中所有key组成的Set集合
		System.out.println(scores.keySet());//[李四, 张三, 孙七]

		//10、entrySet()将Map集合中的每一个key-value转换为一个Entry对象,并返回所有的Entry对象组成的Set集合(多用于Map集合的遍历)
		System.out.println(scores.entrySet());//[李四=81, 张三=99, 孙七=90]

		//11、clear()用于清空集合中所有的数据
		scores.clear();
		System.out.println(scores.size());//0
		
		

		
	}
}

发布了34 篇原创文章 · 获赞 8 · 访问量 697

猜你喜欢

转载自blog.csdn.net/weixin_45720626/article/details/105494314