package exam;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Test2 {
public static void main(String[] args) {
//Map的使用
//定义Map
Map MyMap = new HashMap();
//添加一对Key和 Value的数据
MyMap.put("李白","君不见,黄河之水天上来,奔流到海不复回。");
MyMap.put("杜甫","国破山河在,城春草木深。");
//根据给定的key获取value
System.out.print("李白的诗句:");
System.out.println(MyMap.get("李白"));
System.out.print("杜甫的诗句:");
System.out.println(MyMap.get("杜甫"));
//获取map的长度
int size = MyMap.size();
System.out.println("");
System.out.println("MyMap的映射一共有:" + size + "个元素。");
System.out.println("");
//查找key是否在map中
if(MyMap.containsKey("李白")) {
System.out.println("你查找的键在映射中。");
}else {
System.out.println("你查找的键不在映射中。");
}
System.out.println("");
//查找值是否在map中
if(MyMap.containsValue("君不见,黄河之水天上来,奔流到海不复回。")) {
System.out.println("你查找的值在映射中。");
}else {
System.out.println("你查找的值不在映射中。");
}
System.out.println("");
//转化为set
Set MySet = MyMap.entrySet();
System.out.println(MySet);
System.out.println("");
//比较两个映射
Map MyMap2 = new HashMap();
MyMap2.put("李白","君不见,黄河之水天上来,奔流到海不复回。");
MyMap2.put("杜甫","国破山河在,城春草木深。");
if(MyMap.equals(MyMap2)){
System.out.println("两个映射相等。");
}else {
System.out.println("两个不相等。");
}
System.out.println("");
//获取对应的哈希值
int hash = MyMap.hashCode();
System.out.println(hash);
System.out.println("");
//判断映射是否为空
if(MyMap.isEmpty()) {
System.out.println("映射为空。");
}else {
System.out.println("映射不为空。");
}
System.out.println("");
//转化为键的集合
Set keySet = MyMap.keySet();
System.out.println("键的集合是:"+keySet);
System.out.println("");
//添加一个映射
Map MyMap3 = new HashMap();
MyMap3.put("1", "君不见,高堂明镜悲白发,朝如青丝暮成雪。");
MyMap3.put("2","感时花溅泪,恨别鸟惊心。");
MyMap.putAll(MyMap3);;
System.out.println("添加后的映射是:" + MyMap);
System.out.println("");
//获取映射的所有值
Collection values= MyMap.values();
System.out.println("映射的值是:" + values);
System.out.println("");
//移取一对键和值
MyMap.remove("1");
MyMap.remove("2");
System.out.println("移取后的映射是:" + MyMap);
}
}