一、基本介绍
Map是Java中常用的Collection集合之一,用于存储键值对。
通过Map的key可以快速找到对应的value,类似于字典的查询。
常用的Map实现类有HashMap、TreeMap、LinkedHashMap等。
//HashMap示例
Map map = new HashMap();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
System.out.println(map.get("apple")); //输出10
二、取值操作
1. 使用get方法
Map中最基本的取值方法是使用get方法,传入对应的key即可得到对应的value。
Map map = new HashMap();
map.put("name", "张三");
map.put("age", "18");
String name = map.get("name");
String age = map.get("age");
System.out.println("我的名字叫:" + name);
System.out.println("我今年" + age + "岁了");
2. 遍历取值
可以使用Map的迭代器进行遍历取值,也可以使用foreach语法糖简化操作。
2.1 迭代器
使用迭代器取出Map中的键值对。
Map map = new HashMap();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
Iterator<Map.Entry> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = iter.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
2.2 foreach
使用foreach语法糖取出Map中的键值对。
Map map = new HashMap();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
for(Map.Entry entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
3. 判断键、值是否存在
使用Map的containsKey和containsValue方法可以判断Map中是否存在指定的键或值。
3.1 containsKey
判断Map中是否包含指定的键。
Map map = new HashMap();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
if(map.containsKey("apple")) {
System.out.println("含有apple键");
} else {
System.out.println("不含有apple键");
}
3.2 containsValue
判断Map中是否包含指定的值。
Map map = new HashMap();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
if(map.containsValue(20)) {
System.out.println("含有值为20的项");
} else {
System.out.println("不含有值为20的项");
}
4. 取出所有键或所有值
可以使用Map的keySet和values方法来分别取出所有键或所有值。
4.1 keySet
取出Map中所有的键。
Map map = new HashMap();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
Set keySet = map.keySet();
for(String key : keySet) {
System.out.println(key);
}
4.2 values
取出Map中所有的值。
Map map = new HashMap();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
Collection values = map.values();
for(Integer value : values) {
System.out.println(value);
}
三、总结
通过get方法、遍历、判断键值是否存在、取出所有键和所有值等方法,可以方便地从Map中获取指定的值。
在实际开发中,常常需要使用Map来存储数据,掌握Map的相关操作可以帮助我们更高效地进行开发。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/248714.html
微信扫一扫
支付宝扫一扫