To find the frequency of each character in a String you can take help of a HashMap or Hashtable.
Below is the code for the same:
public class Manager{ public static void main(String[] args) { String str="ABCD abcd"; Map<Character, Integer> occurences=new HashMap<>(); for(char character: str.toCharArray()) { Integer count=occurences.get(character); if(count == null) { count = 0; } count++; occurences.put(character, count); } System.out.println(occurences); } }
Find the lowest/highest frequency of characters in a string using java:
You can add 2 more block of code- one to find the lowest and highest number in map and one to print the desired item. The above code is rewritten as well:
public class Manager { public static void main(String[] args) { String str="my name is Prasanna"; Map map=new LinkedHashMap(); char[] arr=str.toCharArray(); for(int i=0;i<arr.length;i++) { Integer value=(Integer)map.get(arr[i]); if(value == null) { map.put(arr[i], 1); }else { value++; map.put(arr[i], value); } } System.out.println("Frequency of each character : "+ map); //find the min and max frequency in the map: Integer minValue=1; Integer maxValue=1; for(Object key: map.keySet()){ Integer value=(Integer)map.get(key); if(value > maxValue) maxValue=value; else minValue=value; } System.out.println("Min frequency: "+minValue); System.out.println("Max frequency: "+maxValue); for(Object key: map.keySet()){ Integer value=(Integer)map.get(key); if(value == minValue) { System.out.println("First item having lowest frequency : " + key); break; } } } }