返回
揭秘 Java 8 中神奇的 Map 数据结构
前端
2023-09-19 11:59:15
Java 8 中的 Map 数据结构
Map 是一种数据结构,它将键值对存储在一个集合中。键值对由键(key)和值(value)组成,键用于唯一标识值。Map 的主要特点是快速查找,通过键可以迅速找到相应的值。
Map 的基本操作
- 添加键值对:
map.put("key1", "value1");
map.put("key2", "value2");
- 获取值:
String value = map.get("key1");
- 删除键值对:
map.remove("key1");
- 判断键是否存在:
booleancontainsKey= map.containsKey("key1");
- 判断值是否存在:
booleancontainsValue= map.containsValue("value1");
- 获取键值对的数量:
int size = map.size();
Map 的高级用法
- 通过 Map.entrySet() 遍历键值对:
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
- 通过 forEach() 和 lambda 表达式遍历键值对:
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
- 使用 Streams API 处理 Map:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// 过滤键值对
Map<String, Integer> filteredMap = map.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// 转换键值对
Map<Integer, String> invertedMap = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
// 排序键值对
Map<String, Integer> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
结语
Java 8 中的 Map 数据结构功能强大,灵活性高,是开发人员必备的工具。通过掌握 Map 的基本操作和高级用法,可以轻松处理各种数据操作任务,提升开发效率。