Problem: Count Frequencies of Elements using HashMap in Java
Problem Explanation:
Given an array of integers, the task is to count the frequency of each element in the array.
You need to output how many times each integer appears in the array.
Example:
Input:
arr = {1, 2, 2, 3, 4, 4, 4, 5}
Output:
{1=1, 2=2, 3=1, 4=3, 5=1}
Approach using get():
1. For each element in the array:
- Check if the element is already present in the HashMap using containsKey().
- If the key exists, retrieve the current value with get(), increment it by 1, and update the value in
the map using put().
- If the key does not exist, initialize the element with a value of 1.
Code Example:
import [Link];
public class FrequencyCounter {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 4, 5}; // Array to count frequencies
// Create a HashMap to store frequencies
HashMap<Integer, Integer> freqMap = new HashMap<>();
// Traverse the array and count frequencies
for (int num : arr) {
// Check if the number is already in the map
if ([Link](num)) {
// If yes, increment its count
[Link](num, [Link](num) + 1);
} else {
// If no, initialize it with count 1
[Link](num, 1);
// Print the frequency map
[Link](freqMap);