19 Apr 2024

Frequency of Numbers in hashMap java

Problem find the frequency of number in array using HashMap 

In this post, we will explore how to find the frequency of each number in an array using a HashMap in Java. This approach is efficient and easy to implement. Let’s break down the problem with code and explanation.

Input:

6

[2,5,7,1,2,5]

Output:

1 1

2 2

5 2

7 1

import java.util.*;

public class hello(){

public static void main(String args[]){

        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();

        int n=sc.nextInt();

        for(int i=0;i<n;i++){

            int temp=sc.nextInt();

            if(map.containsKey(temp)){

                int value=map.get(temp);

                map.replace(temp,++value);

            }

            else{

                map.put(temp,1);

            }

        }

        for (Map.Entry<Integer, Integer> e : map.entrySet()) 

            System.out.println(e.getKey() + " "+ e.getValue());

    }

Explanation

  1. Input:

    • First, the program reads the size of the array, n.
    • Then, it reads n numbers into the array.
  2. Using a HashMap:

    • A HashMap is used to store the numbers as keys and their frequencies as values.
    • If a number is already present in the map (map.containsKey(temp)), its frequency is incremented.
    • If it’s not present, it is added to the map with an initial frequency of 1.
  3. Output:

    • Finally, the program iterates through the HashMap and prints each key (number) with its corresponding value (frequency).

Example Input and Output

Input:


6 2 5 7 1 2 5

Process:

  • Numbers in the array: [2, 5, 7, 1, 2, 5]
  • After processing:
    • 1 appears once.
    • 2 appears twice.
    • 5 appears twice.
    • 7 appears once.

Output:


1 1 2 2 5 2 7 1

Edge Cases to Consider

  1. Array with Repeated Numbers: The program works efficiently even if all numbers are the same. Input: [5, 5, 5, 5]
    Output:


    5 4
  2. Empty Array: If n == 0, the program will output nothing, which is the correct behavior. However, you can add a check to handle this explicitly.

  3. Negative Numbers: The program handles negative numbers naturally, as HashMap keys can be any integer.


Conclusion

Using a HashMap to find the frequency of numbers in an array is both intuitive and efficient. This approach is suitable for arrays of any size and works seamlessly with positive, negative, or repeated numbers.


No comments:

Post a Comment