當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。