DEV Community

realNameHidden
realNameHidden

Posted on

2 1 1 1 1

how to find the frequency of characters in given string in java

Code:

import java.util.*;
import java.lang.*;
class Demo{
    public static void main(String[] args){
        String name = "idiot";
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i=0;i<name.length();i++){
            Character ch = name.charAt(i);
            map.put(ch,map.getOrDefault(ch,0)+1);
        }
        System.out.println(map);
        for(Map.Entry<Character,Integer> e : map.entrySet()){
            System.out.println(e.getKey()+" "+e.getValue());
        }
    }   

}
Enter fullscreen mode Exit fullscreen mode

o/p:

Image description

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more