Collections.frequency用于统计集合中某元素出现次数,接收集合与目标对象,遍历集合通过equals比较,返回匹配次数。支持基本包装类型与自定义对象,后者需重写equals和hashCode方法;可统计null值,但集合本身不能为null,时间复杂度O(n)。

Collections.frequency 是 Java 集合框架中的一个实用方法,用于统计指定集合中某个元素出现的次数。它属于 java.util.Collections 类,使用起来简单高效。
方法定义
public static int frequency(Collection> c, Object o)该方法接收两个参数:
- c:要搜索的集合(不能为 null)
- o:要统计出现次数的对象
返回值是该对象在集合中出现的次数。如果集合包含 null 元素,也可以正确处理。
基本使用示例
下面是一个简单的例子,统计字符串列表中某个单词的出现频率:
立即学习“Java免费学习笔记(深入)”;
Shopxp购物系统历经多年的考验,并在推出shopxp免费购物系统下载之后,收到用户反馈的各种安全、漏洞、BUG、使用问题进行多次修补,已经从成熟迈向经典,再好的系统也会有问题,在完善的系统也从在安全漏洞,该系统完全开源可编辑,当您下载这套商城系统之后,可以结合自身的技术情况,进行开发完善,当然您如果有更好的建议可从官方网站提交给我们。Shopxp网上购物系统完整可用,无任何收费项目。该系统经过
import java.util.*; Listwords = Arrays.asList("apple", "banana", "apple", "orange", "apple"); int count = Collections.frequency(words, "apple"); System.out.println(count); // 输出: 3
统计基本类型和自定义对象
该方法也适用于 Integer、Double 等包装类型:
Listnumbers = Arrays.asList(1, 2, 3, 2, 2, 4); int count2 = Collections.frequency(numbers, 2); System.out.println(count2); // 输出: 3
对于自定义对象,必须正确重写 equals 方法,否则无法正确匹配:
class Person {
String name;
Person(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person p = (Person)o;
return name.equals(p.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
List people = Arrays.asList(
new Person("Alice"),
new Person("Bob"),
new Person("Alice")
);
int aliceCount = Collections.frequency(people, new Person("Alice"));
System.out.println(aliceCount); // 输出: 2
注意事项
使用时需注意以下几点:
- 传入的集合不能为 null,否则会抛出 NullPointerException
- 统计 null 值也是合法的,例如 Collections.frequency(list, null) 可以统计 null 出现的次数
- 性能上,该方法会遍历整个集合,时间复杂度为 O(n),不适合频繁调用的大数据量场景
- 确保集合中的元素正确实现了 equals 和 hashCode 方法,尤其是自定义类









