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


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


該方法是一個java.util.Collections類方法。它計算給定列表中指定元素的頻率。它重寫equals()方法以執行比較,以檢查指定的Object與列表中的Object是否相等。
用法:

public static int frequency(Collection c, Object o) 
parameters:
c: Collection in which to determine the frequency of o.
o: Object whose frequency is to be determined.
It throws Null Pointer Exception if the Collection c is null.
// Java program to demonstrate  
// working of Collections.frequency() 
import java.util.*; 
  
public class GFG 
{ 
    public static void main(String[] args) 
    { 
        // Let us create a list with 4 items 
        ArrayList<String> list = 
                        new ArrayList<String>(); 
        list.add("code"); 
        list.add("code"); 
        list.add("quiz"); 
        list.add("code"); 
      
        // count the frequency of the word "code" 
        System.out.println("The frequency of the word code is: "+  
                                Collections.frequency(list, "code"));  
    } 
}

輸出:

The frequency of the word code is: 3

使用Java.util。用於自定義定義對象的Collections.frequency()


上麵提到的方法對於Java中已經定義的對象都很好,但是自定義定義的對象呢?好吧,要計算java中自定義對象的頻率,我們將不得不簡單地重寫equals()方法。讓我們看看我們如何做到這一點。

// Java program to demonstrate working of  
// Collections.frequency() 
// for custom defined objects 
import java.util.*; 
  
public class GFG 
{ 
    public static void main(String[] args) 
    { 
        // Let us create a list of Student type 
        ArrayList<Student> list = 
                        new ArrayList<Student>(); 
        list.add(new Student("Ram", 19)); 
        list.add(new Student("Ashok", 20)); 
        list.add(new Student("Ram", 19)); 
        list.add(new Student("Ashok", 19)); 
         
        // count the frequency of the word "code" 
        System.out.println("The frequency of the Student Ram, 19 is: "+  
                                Collections.frequency(list, new Student("Ram", 19)));  
    } 
} 
class Student 
{ 
    private String name; 
    private int age; 
      
    Student(String name, int age) 
    { 
    this.name=name; 
    this.age=age; 
    } 
      
    public String getName() 
    { 
        return name; 
    } 
      
    public void setName(String name) 
    { 
        this.name = name; 
    } 
  
    public int getAge()  
    { 
        return age; 
    } 
      
    public void setAge(int age) 
    { 
        this.age = age; 
    } 
      
    @Override
    public boolean equals(Object o) 
    { 
        Student s; 
        if(!(o instanceof Student)) 
        { 
            return false; 
        } 
          
        else
        { 
            s=(Student)o; 
            if(this.name.equals(s.getName()) && this.age== s.getAge()) 
            { 
                return true; 
            } 
        } 
        return false; 
    } 
}

輸出:

The frequency of the Student Ram,19 is: 2


相關用法


注:本文由純淨天空篩選整理自 Java.util.Collections.frequency() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。