Collections.frequency() 是 Java 中用于统计元素在 Collection 中精确匹配次数的静态方法,基于 equals() 遍历比较,时间复杂度 O(n),支持 null 元素,但不适用于数组、Map 或条件筛选。

Collections.frequency() 是 Java 集合工具类中的一个静态方法,专门用于统计某个元素在 Collection(如 ArrayList、LinkedList、HashSet 等)中出现的**精确匹配次数**。它内部通过遍历集合、调用 equals() 方法逐个比较实现,不依赖排序或哈希结构,因此通用性强,但时间复杂度为 O(n)。
基本用法:传入集合和目标元素
语法很简单:
int count = Collections.frequency(collection, element);
注意两点:
-
collection必须是非 null 的Collection实例(如ArrayList<String>),否则抛NullPointerException; -
element可以为null,方法会正确统计null元素的个数(前提是集合本身允许存null,如ArrayList可以,TreeSet不行)。
统计字符串列表中某单词出现次数
例如统计 "apple" 在一个水果列表里出现了几次:
立即学习“Java免费学习笔记(深入)”;
List<String> fruits = Arrays.asList("apple", "banana", "apple", "cherry", "apple");
int appleCount = Collections.frequency(fruits, "apple"); // 返回 3
这里比较基于 String.equals(),区分大小写。若要忽略大小写,需先统一转换(frequency 本身不支持自定义比较逻辑):
List<String> lowerFruits = fruits.stream().map(String::toLowerCase).collect(Collectors.toList()); int countIgnoreCase = Collections.frequency(lowerFruits, "apple");
统计自定义对象时要注意 equals() 和 hashCode()
如果集合中是自定义类(如 Person),必须正确重写 equals()(以及推荐同时重写 hashCode()):
class Person {
String name;
int age;
Person(String name, int age) { this.name = name; this.age = age; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() { return Objects.hash(name, age); }
}
然后才能准确统计:
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Alice", 25)
);
int aliceCount = Collections.frequency(people, new Person("Alice", 25)); // 返回 2
不能用于数组或 Map,也不支持条件筛选
Collections.frequency() 只接受 Collection 接口的实现类。常见误区:
- ❌ 不能直接传数组:
Collections.frequency(new String[]{"a","b"}, "a")编译失败(数组不是Collection);需先转成List,如Arrays.asList(arr); - ❌ 不适用于
Map(键或值的统计需用map.values()或map.keySet()提取后再调用); - ❌ 不支持模糊匹配、范围查找或谓词过滤(如“长度大于 5 的字符串个数”),这类需求应改用 Stream API:
list.stream().filter(s -> s.length() > 5).count()。


















