一、基本介紹
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/zh-hant/n/248714.html
微信掃一掃
支付寶掃一掃