Java中Map接口用于存储键值对,常用实现类有HashMap、LinkedHashMap、TreeMap和ConcurrentHashMap,各自适用于不同场景。HashMap基于哈希表实现,查找、插入、删除平均时间复杂度为O(1),不保证顺序,适合大多数无需排序的场景;LinkedHashMap通过双向链表维护插入顺序,适用于需顺序遍历或实现LRU缓存的场景;TreeMap基于红黑树,按键自然顺序或自定义比较器排序,适用于需要有序键的场景,操作时间复杂度为O(logN);ConcurrentHashMap为线程安全设计,采用分段锁或CAS机制,适用于高并发环境。使用Map时需注意:自定义对象作键时必须重写equals()和hashCode()方法,避免因哈希不一致导致无法正确存取;迭代过程中直接修改Map会抛出ConcurrentModificationException,应使用Iterator的remove()方法或延迟修改;为提升性能,可预设HashMap初始容量以减少扩容开销。Java 8新增多种便捷方法:forEach()简化遍历;getOrDefault()提供默认值避免空指针;putIfAbsent()实现存在则不插入;computeIfAbsent()支持延迟计算初始化,常用于构建多值映射;computeIfPresent()和compute()用于条件更新或合并值;merge()可将新值与旧值按规则合并,适用于计数、

Java中Map接口是存储键值对(key-value pairs)的核心工具,它提供了一种高效、灵活的方式,通过唯一的键来快速查找对应的值。你可以把它想象成一本字典,每个词条(键)都对应着一个解释(值),而且每个词条都是独一无二的。
在Java中使用Map存储键值对,通常我们会选择其具体的实现类,比如
HashMap
LinkedHashMap
TreeMap
HashMap
要开始使用,你只需要声明一个Map对象,并指定键和值的类型。例如,如果你想存储学生的ID(整数)和他们的名字(字符串):
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// 声明并初始化一个HashMap
Map<Integer, String> studentNames = new HashMap<>();
// 存储键值对:使用put()方法
studentNames.put(101, "张三");
studentNames.put(102, "李四");
studentNames.put(103, "王五");
studentNames.put(101, "张三丰"); // 键重复时,新的值会覆盖旧的值
System.out.println("Map中的所有学生: " + studentNames); // {101=张三丰, 102=李四, 103=王五}
// 获取值:使用get()方法,传入键
String nameOf102 = studentNames.get(102);
System.out.println("ID为102的学生是: " + nameOf102); // 李四
// 检查键是否存在:使用containsKey()
boolean has103 = studentNames.containsKey(103);
System.out.println("是否存在ID为103的学生? " + has103); // true
// 检查值是否存在:使用containsValue()
boolean hasWangWu = studentNames.containsValue("王五");
System.out.println("是否存在名为王五的学生? " + hasWangWu); // true
// 移除键值对:使用remove()方法
studentNames.remove(102);
System.out.println("移除ID为102的学生后: " + studentNames); // {101=张三丰, 103=王五}
// 获取Map的大小
int size = studentNames.size();
System.out.println("Map中当前学生数量: " + size); // 2
// 遍历Map:
// 1. 遍历键集
System.out.println("所有学生ID:");
for (Integer id : studentNames.keySet()) {
System.out.println(id);
}
// 2. 遍历值集
System.out.println("所有学生姓名:");
for (String name : studentNames.values()) {
System.out.println(name);
}
// 3. 遍历键值对集(推荐,效率更高)
System.out.println("所有学生信息:");
for (Map.Entry<Integer, String> entry : studentNames.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", 姓名: " + entry.getValue());
}
// 使用Java 8的forEach方法遍历
System.out.println("使用forEach遍历:");
studentNames.forEach((id, name) -> System.out.println("ID: " + id + ", 姓名: " + name));
}
}这段代码基本上涵盖了Map接口最常用的操作。你会发现,它的API设计得非常直观,大部分方法名都能顾名思义。
立即学习“Java免费学习笔记(深入)”;
说实话,这真的是个老生常谈但又不得不提的问题。不同的场景对Map的性能、顺序要求都不一样,选错了可能导致性能瓶颈或者逻辑错误。
HashMap
null
null
HashMap
HashMap
equals()
hashCode()
HashMap
LinkedHashMap
HashMap
LinkedHashMap
HashMap
LinkedHashMap
accessOrder
true
HashMap
TreeMap
Comparable
Comparator
TreeMap
Comparable
TreeMap
Comparator
ConcurrentHashMap
java.util.concurrent
Collections.synchronizedMap()
ConcurrentModificationException
ConcurrentHashMap
选择哪个,真的取决于你的具体需求。没有银弹,只有最适合的。
在使用Map时,有些地方一不留神就可能踩坑,或者写出性能不佳的代码。我总结了几个常见的点,希望能帮你避开它们。
自定义对象作为键时,务必重写equals()
hashCode()
HashMap
HashSet
HashMap
put
get
class MyKey {
int id;
String name;
public MyKey(int id, String name) { this.id = id; this.name = name; }
// 没有重写equals和hashCode,后果很严重
// @Override public boolean equals(Object o) { ... }
// @Override public int hashCode() { ... }
}
Map<MyKey, String> myMap = new HashMap<>();
myMap.put(new MyKey(1, "A"), "Value1");
System.out.println(myMap.get(new MyKey(1, "A"))); // 很大几率返回null,因为HashMap认为这两个MyKey对象是不同的equals()
hashCode()
迭代Map时修改Map会导致ConcurrentModificationException
HashMap
ArrayList
map.remove()
map.put()
ConcurrentModificationException
Iterator
remove()
ConcurrentHashMap
初始化HashMap
HashMap
HashMap
HashMap
1 / 加载因子 + 1
// 假设预计存储100个元素 Map<Integer, String> largeMap = new HashMap<>(150); // 100 / 0.75 ≈ 133,取一个稍大的2的幂次,如128或256
Java 8及之后的版本为Map接口引入了许多实用的新方法,让Map的操作更加简洁和高效。这些特性在实际开发中非常方便,能写出更优雅的代码。
forEach(BiConsumer action)
entrySet()
Map<String, Integer> wordCounts = new HashMap<>();
wordCounts.put("apple", 5);
wordCounts.put("banana", 3);wordCounts.forEach((word, count) -> System.out.println(word + ": " + count)); // 输出: // apple: 5 // banana: 3
getOrDefault(Object key, V defaultValue)
null
null
String fruit = wordCounts.getOrDefault("orange", 0).toString(); // getOrDefault返回的是Integer,这里为了打印转String
System.out.println("Orange count: " + fruit); // Orange count: 0putIfAbsent(K key, V value)
null
wordCounts.putIfAbsent("apple", 10); // "apple"已存在,不更新,返回5
wordCounts.putIfAbsent("grape", 2); // "grape"不存在,插入,返回null
System.out.println(wordCounts); // {apple=5, banana=3, grape=2}computeIfAbsent(K key, Function mappingFunction)
mappingFunction
Map<String, List<String>> groupMap = new HashMap<>();
groupMap.computeIfAbsent("A", k -> new ArrayList<>()).add("Alice");
groupMap.computeIfAbsent("B", k -> new ArrayList<>()).add("Bob");
groupMap.computeIfAbsent("A", k -> new ArrayList<>()).add("Amy"); // "A"已存在,直接获取List并添加
System.out.println(groupMap); // {A=[Alice, Amy], B=[Bob]}computeIfPresent(K key, BiFunction remappingFunction)
remappingFunction
null
wordCounts.computeIfPresent("apple", (k, v) -> v + 1); // "apple"存在,值更新为6
wordCounts.computeIfPresent("lemon", (k, v) -> v + 1); // "lemon"不存在,不执行
System.out.println(wordCounts); // {apple=6, banana=3, grape=2}compute(K key, BiFunction remappingFunction)
remappingFunction
null
wordCounts.compute("banana", (k, v) -> v == null ? 1 : v * 2); // "banana"存在,值更新为6
wordCounts.compute("cherry", (k, v) -> v == null ? 1 : v * 2); // "cherry"不存在,插入1
System.out.println(wordCounts); // {apple=6, banana=6, grape=2, cherry=1}merge(K key, V value, BiFunction remappingFunction)
remappingFunction
Map<String, Integer> stock = new HashMap<>();
stock.put("shirt", 10);
stock.merge("shirt", 5, (oldVal, newVal) -> oldVal + newVal); // shirt: 10 + 5 = 15
stock.merge("pants", 8, (oldVal, newVal) -> oldVal + newVal); // pants不存在,直接插入8
System.out.println(stock); // {shirt=15, pants=8}这些新特性真的大大简化了Map的常见操作,让代码更具表达力。我个人特别喜欢
computeIfAbsent
getOrDefault
以上就是如何在Java中使用Map接口存储键值对的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号