Count the frequency of the elements in a List in Java

In this post, we will see how to count the frequency of the elements in a List in Java.

 

1. Using Set

We know that a 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 number of occurrences of the specified element in the list.

 

Download   Run Code

Output:

A: 3
B: 2
C: 1

 

2. Using 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:

 

Download   Run Code

Output:

A: 3
B: 2
C: 1

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word an*d help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz