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

Collections.frequency 是 Java 集合框架中的一个实用方法,用于统计指定集合中某个元素出现的次数。它属于 java.util.Collections 类,使用起来简单高效。
该方法接收两个参数:
返回值是该对象在集合中出现的次数。如果集合包含 null 元素,也可以正确处理。
下面是一个简单的例子,统计字符串列表中某个单词的出现频率:
立即学习“Java免费学习笔记(深入)”;
Shopxp购物系统历经多年的考验,并在推出shopxp免费购物系统下载之后,收到用户反馈的各种安全、漏洞、BUG、使用问题进行多次修补,已经从成熟迈向经典,再好的系统也会有问题,在完善的系统也从在安全漏洞,该系统完全开源可编辑,当您下载这套商城系统之后,可以结合自身的技术情况,进行开发完善,当然您如果有更好的建议可从官方网站提交给我们。Shopxp网上购物系统完整可用,无任何收费项目。该系统经过
1
import java.util.*;
List<String> words = Arrays.asList("apple", "banana", "apple", "orange", "apple");
int count = Collections.frequency(words, "apple");
System.out.println(count); // 输出: 3
该方法也适用于 Integer、Double 等包装类型:
List<Integer> numbers = 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<Person> 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
使用时需注意以下几点:
以上就是在Java中如何使用Collections.frequency的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号