16 May 2024

Count the Frequency of a Number(Using HashMap in Java)

 import java.util.*;


class HelloWorld {

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

        

    }

}

No comments:

Post a Comment