Collections.frequency方法用于统计集合中某元素出现次数,需传入非null集合与目标对象,依赖equals判断,适用于List、Set等Collection集合,自定义类需重写equals和hashCode方法。
Java 中的 Collections.frequency 方法可以用来统计集合中某个元素出现的次数。这个方法属于 java.util.Collections 工具类,使用起来非常方便,但有一些使用前提和注意事项。
方法定义
public static int frequency(Collection> c, Object o)
该方法接收两个参数:
-
c:要搜索的集合(不能为 null)
-
o:要统计出现次数的对象
返回值是该对象在集合中出现的次数(int 类型)。
基本使用示例
以下是一个简单的例子,演示如何统计 List 中某个元素的出现次数:
List list = Arrays.asList("apple", "banana", "apple", "orange", "apple");
int count = Collections.frequency(list, "apple");
System.out.println(count); // 输出:3
支持的数据类型和注意事项
- 适用于所有实现
Collectio
n 接口的集合,如 ArrayList、LinkedList、HashSet 等
- 统计依赖于元素的
equals() 方法,因此自定义对象需要正确重写 equals()
- 如果集合为 null,会抛出
NullPointerException
- 对 Set 集合使用时,结果只能是 0 或 1,因为 Set 不允许重复元素
自定义对象的频率统计
如果你用的是自定义类,比如 Person:
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 Objects.equals(name, p.name);
}
@Override
public int hashCode() { return Objects.hash(name); }
}
然后可以这样统计:
List people = Arrays.asList(
new Person("Alice"),
new Person("Bob"),
new Person("Alice")
);
int count = Collections.frequency(people, new Person("Alice"));
System.out.println(count); // 输出:2
基本上就这些。只要注意集合不为 null,且元素的 equals 正确实现,
Collections.frequency 就能准确返回目标元素的出现次数。