Home » Java programming language

Java Collections frequency() Method with Example

Collections Class frequency() method: Here, we are going to learn about the frequency() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 03, 2020

Collections Class frequency() method

  • frequency() method is available in java.util package.
  • frequency() method is used to return the frequency of the given Object (obj) to the given Collection (co) or in other words, this method is used to return the number of elements in the given collection which is same as the given Object (obj).
  • frequency() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then also we will not get an error.
  • frequency() method may throw an exception at the time of returning frequency.
    NullPointerException: This exception may throw when the given parameter Collection (co) if null exists.

Syntax:

    public static int frequency(Collection co, Object obj);

Parameter(s):

  • Collection co – represents the Collection object in which to calculate the frequency of the given Object (obj).
  • Object obj – represents the object whose frequency is to be calculated.

Return value:

The return type of this method is int, it returns the frequency of the given object with respect to the given collection.

Example:

// Java program is to demonstrate the example
// of int frequency() of Collections

import java.util.*;

public class Frequency {
    public static void main(String args[]) {
        // Instantiate a LinkedList   
        List link_l = new LinkedList();

        // By using add() method is to
        // add elements in linked list
        link_l.add(10);
        link_l.add(20);
        link_l.add(30);
        link_l.add(40);
        link_l.add(50);
        link_l.add(40);
        link_l.add(30);

        // Display LinkedList
        System.out.println("link_l: " + link_l);

        System.out.println();

        // By using frequency() method is to
        // return the object frequency of the
        // given collection linked ist
        int f1 = Collections.frequency(link_l, 40);
        int f2 = Collections.frequency(link_l, 30);

        // Display frequency
        System.out.println("Collections.frequency(link_l,40): " + f1);
        System.out.println("Collections.frequency(link_l,30): " + f2);
    }
}

Output

link_l: [10, 20, 30, 40, 50, 40, 30]

Collections.frequency(link_l,40): 2
Collections.frequency(link_l,30): 2


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.