文章
Rust vs Java 中 HashMap 用法对比
目录
🧩 Rust vs Java 中 HashMap 用法对比#
📋 目录#
- 创建与插入
- 读取元素
- 检查是否存在键
- 遍历
HashMap - 条件插入(
entryvsputIfAbsent/computeIfAbsent) - 计数器模式
- 嵌套结构
- 总结对比
1. 创建与插入#
✅ Rust#
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("apple", 3);
map.insert("banana", 2);
✅ Java#
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 2);
2. 读取元素#
✅ Rust#
if let Some(value) = map.get("apple") {
println!("Found: {}", value);
}
✅ Java#
Integer value = map.get("apple");
if (value != null) {
System.out.println("Found: " + value);
}
3. 检查是否存在键#
✅ Rust#
if map.contains_key("banana") {
println!("We have bananas!");
}
✅ Java#
if (map.containsKey("banana")) {
System.out.println("We have bananas!");
}
4. 遍历 HashMap#
✅ Rust#
for (key, value) in &map {
println!("{key}: {value}");
}
✅ Java#
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
5. 条件插入(防止覆盖)#
✅ Rust 使用 entry().or_insert(...)#
map.entry("apple").or_insert(0); // 如果不存在则插入 0
✅ Java 使用 putIfAbsent() 或 computeIfAbsent()#
map.putIfAbsent("apple", 0); // 不存在才插入
map.computeIfAbsent("apple", key -> 0); // 更灵活,支持函数式逻辑
6. 计数器模式(键出现次数)#
✅ Rust#
let mut counter = HashMap::new();
for word in vec!["apple", "banana", "apple"] {
*counter.entry(word).or_insert(0) += 1;
}
✅ Java#
HashMap<String, Integer> counter = new HashMap<>();
for (String word : List.of("apple", "banana", "apple")) {
counter.put(word, counter.getOrDefault(word, 0) + 1);
}
7. 嵌套结构#
✅ Rust 嵌套 HashMap<String, Vec<String>>#
let mut tag_map: HashMap<String, Vec<String>> = HashMap::new();
tag_map.entry("rust".to_string()).or_default().push("system".to_string());
✅ Java#
HashMap<String, List<String>> tagMap = new HashMap<>();
tagMap.computeIfAbsent("rust", k -> new ArrayList<>()).add("system");
8. 总结对比表#
| 功能 | Rust 用法 | Java 用法 | 说明 |
|---|---|---|---|
| 创建 | HashMap::new() | new HashMap<>() | 类似 |
| 插入 | insert(k, v) | put(k, v) | 类似 |
| 获取 | get(k) | get(k) | 返回 Option vs null |
| 存在性 | contains_key(k) | containsKey(k) | 类似 |
| 条件插入 | entry(k).or_insert(v) | putIfAbsent(k, v) | Java 还支持 computeIfAbsent |
| 遍历 | for (k, v) in &map | for (entry : map.entrySet()) | 类似 |
| 值更新 | *entry += 1 | put(k, getOrDefault(k, 0) + 1) | Rust 可通过解引用 *entry |
💡 总结#
- Rust 的
HashMap借助entry()API 提供了强大的条件操作能力,类似 Java 的computeIfAbsent,但语法更偏向所有权和模式匹配; - Java 的
HashMap更习惯用null来表示缺失值,Rust 用Option<T>; - Java 具备更丰富的内建并发版本(如
ConcurrentHashMap),而 Rust 需借助Mutex<HashMap<...>>或第三方 crate(如dashmap)实现并发。