java如何用map
使用Map的基本方法
在Java中,Map是一种键值对集合,常用的实现类有HashMap、TreeMap和LinkedHashMap。以下是基本用法:
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
// 获取值
int appleCount = map.get("apple");
System.out.println("Apple count: " + appleCount);
// 检查键是否存在
boolean hasBanana = map.containsKey("banana");
System.out.println("Has banana: " + hasBanana);
// 遍历Map
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Map的常见操作
Map提供了多种方法来操作键值对:

// 移除键值对
map.remove("orange");
// 替换值
map.replace("apple", 15);
// 获取所有键
Set<String> keys = map.keySet();
// 获取所有值
Collection<Integer> values = map.values();
// 清空Map
map.clear();
// 检查Map是否为空
boolean isEmpty = map.isEmpty();
不同Map实现类的选择
根据需求选择合适的Map实现类:
HashMap:基于哈希表,无序,插入和查找效率高(O(1))。TreeMap:基于红黑树,按键的自然顺序或自定义顺序排序(O(log n))。LinkedHashMap:保持插入顺序或访问顺序。
// TreeMap示例(按键排序)
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("banana", 20);
treeMap.put("apple", 10);
treeMap.put("orange", 30);
// 输出顺序:apple, banana, orange
// LinkedHashMap示例(保持插入顺序)
Map<String, Integer> linkedMap = new LinkedHashMap<>();
linkedMap.put("banana", 20);
linkedMap.put("apple", 10);
linkedMap.put("orange", 30);
// 输出顺序:banana, apple, orange
处理重复键和空值
Map的键必须是唯一的,值可以为null(取决于实现类):

// 重复键会覆盖旧值
map.put("apple", 10);
map.put("apple", 20); // 旧值10被覆盖
// HashMap允许null键和null值
map.put(null, 5);
map.put("unknown", null);
// TreeMap不允许null键(会抛出NullPointerException)
使用Java 8的增强功能
Java 8为Map添加了新的方法:
// 如果键不存在,则计算值
map.computeIfAbsent("pear", k -> 40);
// 合并值
map.merge("apple", 5, (oldValue, newValue) -> oldValue + newValue);
// 过滤和遍历
map.entrySet().stream()
.filter(entry -> entry.getValue() > 15)
.forEach(entry -> System.out.println(entry.getKey()));
线程安全的Map
在多线程环境中,可以使用ConcurrentHashMap或通过Collections.synchronizedMap包装:
// ConcurrentHashMap(推荐)
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
// 同步包装
Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());






