Wednesday, 31 January 2018

Java Program to Calculate the Frequency of the Strings using HashMap

Tags

Java program to calculate the frequency of the string using HashMap is given below. In this program we first created a HashMap wherer string is the key and its number of occurrence is value. we first input the string then we will check if the string already exists as the key or not. If the string already exists already as a key then we will simply increment its value. Otherwise we will put the key in the HashMap with value 1.

Java Program to calculate the Frequency of the strings using HashMap:


import java.io.*;
import java.util.*;

public class stringFrequency{

    public static void main(String[] args) {
       
         Scanner in=new Scanner(System.in);
         System.out.println("\nEnter the number of strings: ");
         int n=in.nextInt();
         
        //creating hashmap object where String will be
        //String will be key and its frequency will be value
         HashMap<String,Integer> hm=new HashMap<String,Integer>();
         System.out.println("\nEnter the strings: ");


         for(int i=0;i<n;i++){
              String s=in.next();
             
              //checking if key exists already
              if(hm.containsKey(s)){
                  
                  //if key exist then we increment the value
                  hm.put(s,hm.get(s)+1);
              }
              else{
                  
                  //if key not exit then we put the key with value 1
                  hm.put(s,1);
              }
         }
        
         System.out.println("\nThe frequency of the strings are given: ");
         for(String key: hm.keySet()){

              System.out.printf("%-20s%d%n",key,hm.get(key));
         }
        
    }
}


OUTPUT:




EmoticonEmoticon