海南封关,你应该知道的10个新常识
2025/12/18 22:54:50
在Java中,Map是一个非常重要的接口,它表示键值对(Key-Value)的映射集合。Map 不允许重复的键,每个键最多只能映射到一个值。
键唯一性:不允许重复的键
键值对存储:每个元素包含一个键和一个值
无序(某些实现类有序):不保证元素的顺序
import java.util.*; // 创建 HashMap Map<String, Integer> hashMap = new HashMap<>(); // 添加元素 hashMap.put("Alice", 25); hashMap.put("Bob", 30); hashMap.put("Charlie", 28); // 获取元素 int age = hashMap.get("Alice"); // 25 // 遍历 Map for (Map.Entry<String, Integer> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }// 保持插入顺序 Map<String, Integer> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put("Zoe", 22); linkedHashMap.put("Alice", 25); linkedHashMap.put("Bob", 30); // 遍历时保持插入顺序 for (String key : linkedHashMap.keySet()) { System.out.println(key); // Zoe, Alice, Bob }// 按键的自然顺序或自定义比较器排序 Map<String, Integer> treeMap = new TreeMap<>(); treeMap.put("Zoe", 22); treeMap.put("Alice", 25); treeMap.put("Bob", 30); // 遍历时按键排序 for (String key : treeMap.keySet()) { System.out.println(key); // Alice, Bob, Zoe }Map<String, String> map = new HashMap<>(); // 添加元素 map.put("key1", "value1"); map.put("key2", "value2"); // 获取元素 String value = map.get("key1"); // 检查键是否存在 boolean exists = map.containsKey("key1"); // 检查值是否存在 boolean valueExists = map.containsValue("value1"); // 删除元素 map.remove("key1"); // 获取大小 int size = map.size(); // 检查是否为空 boolean isEmpty = map.isEmpty(); // 获取所有键的集合 Set<String> keys = map.keySet(); // 获取所有值的集合 Collection<String> values = map.values(); // 获取所有键值对的集合 Set<Map.Entry<String, String>> entries = map.entrySet(); // 清空Map map.clear();Map<String, Integer> map = new HashMap<>(); // putIfAbsent - 如果键不存在则添加 map.putIfAbsent("key1", 100); // compute - 计算新值 map.compute("key1", (k, v) -> v == null ? 0 : v + 1); // computeIfAbsent - 如果键不存在则计算新值 map.computeIfAbsent("key2", k -> 50); // computeIfPresent - 如果键存在则计算新值 map.computeIfPresent("key1", (k, v) -> v * 2); // merge - 合并值 map.merge("key1", 10, (oldValue, newValue) -> oldValue + newValue); // forEach - 遍历 map.forEach((k, v) -> System.out.println(k + ": " + v)); // getOrDefault - 获取值或默认值 int value = map.getOrDefault("nonexistent", 0);import java.util.concurrent.ConcurrentHashMap; // 线程安全的 HashMap Map<String, Integer> concurrentMap = new ConcurrentHashMap<>(); concurrentMap.put("key1", 100);// 将普通 Map 转换为线程安全的 Map Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());public class MapExample { public static void main(String[] args) { // 统计单词出现次数 String text = "hello world hello java world java programming"; String[] words = text.split(" "); Map<String, Integer> wordCount = new HashMap<>(); for (String word : words) { wordCount.merge(word, 1, Integer::sum); } // 输出结果 wordCount.forEach((word, count) -> System.out.println(word + ": " + count)); } }Map 是 Java 集合框架中非常实用的数据结构,广泛应用于缓存、配置管理、数据统计等场景。