This post will discuss how to count the frequency of the elements in a list in Java.

1. Using a Set

We know that set stores only distinct entries. The idea is to get distinct elements in the list by inserting all elements in the set & then call static method frequency(Collection<?> c, Object o) provided by the Collections class for each distinct element. frequency() returns the total number of occurrences of the specified element in the list.

Download  Run Code

Output:

A: 3
B: 2
C: 1

2. Using a Map

Instead of storing the distinct elements in the set and then calling Collections.frequency() for each distinct element, we can construct a map that stores the frequencies of the elements present in a list.

Download  Run Code

Output:

A: 3
B: 2
C: 1

 
We can even simplify things by using streams in Java 8 and above:

Download  Run Code

Output:

A: 3
B: 2
C: 1

 
Here’s a version without streams (works with Java 8 and above):

Download  Run Code

Output:

A: 3
B: 2
C: 1

That’s all about counting the frequency of elements in a List in Java.