Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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
Advertisements
