Java中Map的增删改查
•文章
48 0
前言
在Java中,Map是一种键值对的集合,用于存储键值对关联关系。Map中的键是唯一的,每个键对应一个值。常用的Map实现类有HashMap、LinkedHashMap和TreeMap。以下以HashMap为例,简要介绍Java中Map的增删改查操作:
创建一个HashMap实例并添加键值对:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 5);
map.put("Banana", 3);
map.put("Cherry", 10);
System.out.println(map); // 输出:{Apple=5, Banana=3, Cherry=10}
}
}
按键删除键值对:
map.remove("Banana");
System.out.println(map); // 输出:{Apple=5, Cherry=10}
删除所有键值对:
map.clear();
System.out.println(map); // 输出:{}
修改指定键对应的值:
map.put("Apple", 8);
System.out.println(map); // 输出:{Apple=8, Cherry=10}
根据键获取对应的值:
int value = map.get("Apple");
System.out.println(value); // 输出:8
遍历Map的键值对:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " = " + value);
}
检查Map中是否包含某个键:
boolean containsKey = map.containsKey("Cherry");
System.out.println(containsKey); // 输出:true
检查Map中是否包含某个值:
boolean containsValue = map.containsValue(10);
System.out.println(containsValue); // 输出:true
以上就是Java中Map的基本增删改查操作。请注意,由于HashMap的无序性,遍历时键值对的顺序可能与添加时不同。如果需要保留键值对的插入顺序,可以使用LinkedHashMap。如果需要对键进行排序,可以使用TreeMap。
版权属于:戏人看戏博客网
本文链接:https://day.nb.sb/archives/500.html
若无注明均为戏人看戏原创,转载请注明出处,感谢您的支持!