Java统计数组元素频次最常用HashMap,时间复杂度O(n);也可用Stream API简化写法;整数范围有限时可用索引数组提升效率;进阶需求如频次排序可用stream.sorted或PriorityQueue实现Top-K。

Java 中统计数组中各元素出现频次,核心思路是用键值对结构记录“元素 → 次数”,最常用且推荐的方式是使用 HashMap。不同数据类型(如 int、String)处理方式略有差异,但逻辑一致。
基本方法:用 HashMap 统计(适用于任意类型)
遍历数组,对每个元素:若已存在则次数 +1,否则初始化为 1。
- 对于 String 数组,可直接用字符串作 key
- 对于 int 数组,需注意自动装箱(int → Integer),HashMap 支持
- 代码简洁,时间复杂度 O(n),空间复杂度 O(唯一元素个数)
示例(int 数组):
int[] arr = {1, 2, 2, 3, 3, 3};
Map<Integer, Integer> freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
// 结果:{1=1, 2=2, 3=3}
简化写法:Java 8 Stream API(一行流式统计)
适合函数式风格,可读性好,但性能略低于传统循环(小数据量无感)。
立即学习“Java免费学习笔记(深入)”;
- 用
Collectors.groupingBy+Collectors.counting() - 注意:Stream 处理基本类型数组需先转为包装类型流(如
Arrays.stream(arr).boxed())
示例(String 数组):
String[] words = {"apple", "banana", "apple", "cherry"};
Map<String, Long> freq = Arrays.stream(words)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
整数范围有限时:用数组代替 HashMap(高效且省内存)
当元素值在较小固定范围内(如 0~1000),可用索引数组直接计数,避免哈希开销。
- 声明长度为
maxValue + 1的 int 数组 - 遍历时以元素值为下标,对应位置自增
- 仅适用于非负整数,且最大值不过大(否则浪费空间)
示例(统计 0~9 的数字频次):
int[] digits = {1, 3, 3, 7, 1, 3};
int[] count = new int[10]; // 索引 0~9
for (int d : digits) {
count[d]++;
}
// count[1] == 2, count[3] == 3...
进阶需求:按频次排序或找高频元素
统计完后常需进一步分析,比如找出出现最多的前 N 个元素。
- 将 HashMap 转为 List<Map.Entry>,用 Collections.sort 或 stream.sorted 自定义排序
- 按 value(频次)降序,再取前几个即可
- 也可用 PriorityQueue 实现 Top-K,适合大数据量
示例(按频次降序取前 2):
freq.entrySet().stream()
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
.limit(2)
.forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));


















