📜  Java中的Java .util.Collections.frequency()

📅  最后修改于: 2022-05-13 01:55:10.963000             🧑  作者: Mango

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 list =
                        new ArrayList();
        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 list =
                        new ArrayList();
        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