当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Java.util.Collections.frequency()用法及代码示例


java.util.Collections类中提供了java.util.Collections.frequency()方法。它用于获取出现在指定Collection列表中的元素的频率。更正式地说,它返回集合中元素e的数量。

用法

public static int frequency(Collection<?> c, Object o)
参数:
c - the collection in which to determine the frequency of o
o - the object whose frequency is to be determined
返回:
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<String>  mylist = new ArrayList<String>(); 
        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

How to Quickly get frequency of an element in an array in 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


相关用法


注:本文由纯净天空筛选整理自 Java.util.Collections.frequency() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。