java 中统计 hashmap 的值可以使用 stream api 的 collectors.groupingby() 方法,将 map 的 entryset() 转换为流后按值分组并计数。具体做法是调用 map.values().stream() 获取值的流,使用 collectors.groupingby(function.identity(), collectors.counting()) 进行聚合,最终得到一个以值为键、出现次数为值的 map<k long></k>。如果输入为空或包含空值,该方法会正常处理,空值也会作为一个独立的键被统计。

如何统计 HashMap 中特定值的出现频率
要统计 HashMap 中某个特定值(例如字符串 "apple")的出现频率,可以直接复用上述流式操作的结果,或者在流中增加过滤条件。通过 filter(entry -> "apple".equals(entry.getValue())) 筛选出目标条目,再使用 count() 终端操作即可得到该值的频次。这种方法避免了全量分组,性能更优,适用于只需查询单一值频次的场景。

一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "apple");
map.put("b", "banana");
map.put("c", "apple");
map.put("d", null);
// 统计所有值的频率
Map<String, Long> frequency = map.values().stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
System.out.println("All frequencies: " + frequency);
// 统计特定值 "apple" 的频率
long appleCount = map.values().stream()
.filter(v -> "apple".equals(v))
.count();
System.out.println("Apple count: " + appleCount);
}
}
预期输出: All frequencies: {null=1, banana=1, apple=2} Apple count: 2
如何处理 HashMap 中包含 null 值的统计情况
当 HashMap 中包含 null 值时,Collectors.groupingBy() 会将 null 视为一个有效的键,并在结果 Map 中生成一个对应的条目。例如,如果原 Map 中有两个 null 值,结果 Map 中会有一个键为 null、值为 2L 的条目。这种行为符合 Java 8+ Stream API 的设计规范,无需额外判空逻辑即可正确统计。
立即学习“Java免费学习笔记(深入)”;

import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, null);
map.put(2, "test");
map.put(3, null);
Map<String, Long> result = map.values().stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
System.out.println("Result with nulls: " + result);
}
}
预期输出: Result with nulls: {null=2, test=1}

















