map集合相关操作
import java.util.HashMap;
import java.util.Map;
public class mapTest {
/**
* map 集合
*/
public static void main(String[] args) {
// 创建一个HashMap实例,存放的数据是键值对 key-value
//key 和 value 可以自定义数据类型,也可以是Object
Map<Integer, String> map = new HashMap<>();
// 添加键值对
map.put(1, "丫丫");
map.put(2, "花花");
map.put(3, "萌兰");
System.out.println("map集合中的大熊猫:"+map);
// 获取与键关联的值
String panda = map.get(1);
System.out.println("获取key为1对应的熊猫:"+panda); // 输出: 1
// 检查键是否存在
boolean isExistKeyOne = map.containsKey(1);
System.out.println("判断map集合中是否存在对于的key:"+isExistKeyOne);
boolean isExistKeyTwo = map.containsKey(4);
System.out.println("判断map集合中是否存在对于的key:"+isExistKeyTwo);
if (map.containsKey(1)) {
System.out.println("获取键对于的值: " + map.get(1));
}
// 遍历Map
for (Map.Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " -> " + value);
}
//修改map中的数据
map.put(1,"萌兰");
System.out.println("修改后map集合中的大熊猫:"+map);
// 删除键值对
map.remove(1);
System.out.println("删除后map集合中的大熊猫:"+map);
// 清空Map
map.clear();
System.out.println("清空后map集合中的大熊猫:"+map);
}
}
得到的打印结果
map集合中的大熊猫:{1=丫丫, 2=花花, 3=萌兰}
获取key为1对应的熊猫:丫丫
判断map集合中是否存在对于的key:true
判断map集合中是否存在对于的key:false
获取键对于的值: 丫丫
1 -> 丫丫
2 -> 花花
3 -> 萌兰
修改后map集合中的大熊猫:{1=萌兰, 2=花花, 3=萌兰}
删除后map集合中的大熊猫:{2=花花, 3=萌兰}
清空后map集合中的大熊猫:{}