Check the frequency of an element in Java with Collections.frequency


Create a List in Java −

List< String >list = Arrays.asList("P","Q","R","P","T","P","U","V","W","X","W" );

Now, let’s say you want to get the frequency of element P. For that, use the Collections.frequency() method −

Collections.frequency(list, "P");

A shown above, we can find the occurrence of any letter as well −

Collections.frequency(list, "T");

Example

 Live Demo

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String>list = Arrays.asList("P","Q","R","P","T","P","U","V","W","X","W" );
      int checkOccurrence = Collections.frequency(list, "P");
      System.out.println("Occurrence of P = " + checkOccurrence);
      checkOccurrence = Collections.frequency(list, "W");
      System.out.println("Occurrence of W = " + checkOccurrence);
      checkOccurrence = Collections.frequency(list, "T");
      System.out.println("Occurrence of T = " + checkOccurrence);
   }
}

Output

Occurrence of P = 3
Occurrence of W = 2
Occurrence of T = 1

Updated on: 30-Jul-2019

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements