package com.javahelp.stringprog;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class CharFrequencyCount {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine(); // enter the string
HashMap<Character, Integer> hm=new HashMap<Character, Integer>();
int count=0; // variable to store count value
for(int i=0; i<s.length(); i++)
{
// check charcter exist in map or not
if(hm.containsKey(s.charAt(i)))
{
count=hm.get(s.charAt(i))+1;
// get the value of map and then store it again with increment by 1
hm.put(s.charAt(i), count);
}
else
{
count=1;
// new character add in map with count value 1
hm.put(s.charAt(i),count);
}
}
// to iterate the hashmap convert hashmap into set
Set set=hm.entrySet();
Iterator it=set.iterator();
while(it.hasNext())
{
// set elements return entry value so typecast with enty
Map.Entry entry=(Map.Entry) it.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
No comments:
Post a Comment