Create a Frequency Map in Java 8

Given a set of words, create a frequency map out of it in Java 8.


 

In Java 8, we can convert the given set of words to stream and use a collector to count the occurrences of elements in a Stream.

The groupingBy(classifier, downstream) collector converts the collection of elements into a Map by grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

 

Download   Run Code

Output:

{A=3, B=1, C=2}

 
For Java 7 and before, here’s naive solution to create a frequency map:

 

Download   Run Code

Output:

{A=3, B=1, C=2}

 
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 and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

Notify of
avatar
wpDiscuz