Print characters and their frequencies in order of occurrence using a LinkedHashMap in Java
Given a string str containing only lowercase characters. The task is to print the characters along with their frequencies in the order of their occurrence in the given string.
Examples:
Input: str = “geeksforgeeks”
Output: g2 e4 k2 s2 f1 o1 r1
Input: str = “helloworld”
Output: h1 e1 l3 o2 w1 r1 d1
Approach: Traverse the given string character by character and store the frequencies of all the strings in a LinkedHashMap which maintains the order of the elements in which they are stored. Now, iterate over the elements of the LinkedhashMap and print the contents.
Below is the implementation of the above approach:
Java
import java.util.LinkedHashMap;
public class GFG {
static void printCharWithFreq(String str, int n)
{
LinkedHashMap<Character, Integer> lhm
= new LinkedHashMap<Character, Integer>();
for ( int i = 0 ; i < n; i++) {
char c = str.charAt(i);
lhm.put(c, lhm.getOrDefault(c, 0 ) + 1 );
}
lhm.forEach(
(k, v) -> System.out.print(k + " " + v));
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
int n = str.length();
printCharWithFreq(str, n);
}
}
|
Output:
g2 e4 k2 s2 f1 o1 r1
Last Updated :
27 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...