在Java中,Map元素存储在键/值对中, Map是接口,因此无法从中创建对象
为了使用Map接口的功能,可以使用以下几种类
- HashMap
- EnumMap
- LinkedHashMap
- WeakHashMap
- TreeMap
下面代码是 Map的常见用法总结
package com.asdi.idea;
import java.util.HashMap;
import java.util.Map;
public class ExampleMap{
public static void main(String[] args) {
System.out.println("hello wangjing");
Map<Integer, String> map = new HashMap<>();
// 1. put(K,V) - 将键K和值V的关联插入到map中。如果键已经存在,则新值将替换旧值。
map.put(1, "aa");
map.put(2, "bb");
System.out.println("map = " + map); // map = {1=aa, 2=bb}
//2. get 根据 key 获取对应的 value 值,如果 key 不存在,则返回 null
System.out.println("map.get(1) = " + map.get(1)); // map.get(1) = aa
//3. containsKey(K) - 检查指定的键K是否在map中。
System.out.println("map.containsKey(1) = " + map.containsKey(1));
//输出为 map.containsKey(1) = true
//4. containsValue(V) - 检查指定的值V是否存在于map中。
//5. replace(K,V) - 将键K的值替换为新的指定值V。
map.replace(2, "xxxx");
System.out.println(" map = " +map ); // map = {1=aa, 2=xxxx}
//6. replace(K,oldValue,newValue) -
// 仅当键K与值oldValue相关联时,才用新值newValue替换键K的值。
//7. keySet() -返回Map集合中存在的所有键的集合
System.out.println("map.keySet() = " + map.keySet()); // map.keySet() = [1, 2]
//8. values() -返回一组包含在Map集合中的所有值
System.out.println("values = " + map.values()); //values = [aa, xxxx]
//9. entrySet() -返回map中存在的所有键/值映射的集合
System.out.println("map.entrySet() = " + map.entrySet());
// 输出为 map.entrySet() = [1=aa, 2=xxxx]
// 10. remove(K) - 从键K表示的Map中删除条目。
// 11. remove(K,V) - 从Map集合中删除键K与值V相关联的条目
// 12. putAll() - 将指定Map集合中的所有条目插入此Map集合中
// 13. putIfAbsent(K,V) - 如果键K尚未与value关联,则插入关联V。
// 14. getOrDefault(K,defaultValue) - 返回与指定键K关联的值。如果找不到键,则返回
// defaultValue。
}
}