Print characters and their frequencies in the order of occurrence
Given string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class PrintCharFreq {
static void my_fun(String str,LinkedHashMap<Character,Integer> freq){
for(char c : str.toCharArray()){
freq.put(c,freq.getOrDefault(c,0)+1);
}
}
public static void main(String[] args) {
LinkedHashMap<Character,Integer> freq = new LinkedHashMap<>();
Scanner sc = new Scanner(System.in);
String str = sc.next();
my_fun(str,freq);
for(Map.Entry<Character,Integer> cur : freq.entrySet()){
System.out.println(cur.getKey() +" " + cur.getValue());
}
}
}