0% found this document useful (0 votes)
13 views2 pages

Count Element Frequencies in Java HashMap

The document describes a problem of counting the frequency of elements in an integer array using a HashMap in Java. It provides an example input and output, along with a step-by-step approach and a code implementation. The code iterates through the array, updating the frequency count for each integer in the HashMap.

Uploaded by

Mohammad asif
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Count Element Frequencies in Java HashMap

The document describes a problem of counting the frequency of elements in an integer array using a HashMap in Java. It provides an example input and output, along with a step-by-step approach and a code implementation. The code iterates through the array, updating the frequency count for each integer in the HashMap.

Uploaded by

Mohammad asif
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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);

You might also like