Create a Frequency Map in Java 8 and above
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; class Main { // Program to create a frequency map in Java 8 and above public static void main(String[] args) { String[] chars = { "A", "B", "C", "A", "C", "A" }; Map<String, Long> freq = Stream.of(chars) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(freq); } } |
Output:
{A=3, B=1, C=2}
Here’s a version without using streams:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.HashMap; import java.util.Map; class Main { public static void main(String[] args) { String[] chars = { "A", "B", "C", "A", "C", "A" }; Map<String, Long> freq = new HashMap<>(); for (String s: chars) { freq.merge(s, 1L, Long::sum); } System.out.println(freq); } } |
Output:
{A=3, B=1, C=2}
For Java 7 and before, here’s a naive solution to create a frequency map:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.HashMap; import java.util.Map; class Main { // A naive solution to create a frequency map in Java public static void main(String[] args) { String[] chars = { "A", "B", "C", "A", "C", "A" }; Map<String, Integer> freq = new HashMap<>(); for (String s: chars) { int prev = 0; // get the previous count if (freq.get(s) != null) { prev = freq.get(s); } freq.put(s, prev + 1); } System.out.println(freq); } } |
Output:
{A=3, B=1, C=2}
That’s all about creating a frequency Map in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)