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

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 method 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}

 
Here’s a version without using streams:

Download  Run Code

Output:

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

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

Download  Run Code

Output:

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

That’s all about creating a frequency Map in Java.