Java中的Java .util.Collections.frequency() 和示例
Java.util.Collections.frequency()方法存在于Java.util.Collections 类中。它用于获取指定集合列表中存在的元素的频率。更正式地说,它返回集合中元素 e 的数量。
句法
public static int frequency(Collection> c, Object o)
Parameters :
c - the collection in which to determine the frequency of o
o - the object whose frequency is to be determined
Returns :
Returns the number of elements in the specified collection
equal to the specified object.
Throws:
NullPointerException - if c is null
// Java program to demonstrate working of
// java.utils.Collections.frequency()
import java.util.*;
public class FrequencyDemo
{
public static void main(String[] args)
{
// Let us create a list of strings
List mylist = new ArrayList();
mylist.add("practice");
mylist.add("code");
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
// Here we are using frequency() method
// to get frequency of element "code"
int freq = Collections.frequency(mylist, "code");
System.out.println(freq);
}
}
输出:
2
如何在Java中快速获取数组中元素的频率?
Java中的数组类没有频率方法。但是我们也可以使用 Collections.frequency() 来获取数组中元素的频率。
// Java program to get frequency of an element
// with java.utils.Collections.frequency()
import java.util.*;
public class FrequencyDemo
{
public static void main(String[] args)
{
// Let us create an array of integers
Integer arr[] = {10, 20, 20, 30, 20, 40, 50};
// Please refer below post for details of asList()
// https://www.geeksforgeeks.org/array-class-in-java/
int freq = Collections.frequency(Arrays.asList(arr), 20);
System.out.println(freq);
}
}
输出:
3