Sunday, October 5, 2025
HomeData Modelling & AIPrint characters and their frequencies in order of occurrence using a LinkedHashMap...

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 = “neveropen” 
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




// Java implementation of the approach
import java.util.LinkedHashMap;
 
public class GFG {
 
    // Function to print the characters and their
    // frequencies in the order of their occurrence
    static void printCharWithFreq(String str, int n)
    {
 
        // LinkedHashMap preserves the order in
        // which the input is supplied
        LinkedHashMap<Character, Integer> lhm
            = new LinkedHashMap<Character, Integer>();
 
        // For every character of the input string
        for (int i = 0; i < n; i++) {
 
            // Using java 8 getorDefault method
            char c = str.charAt(i);
            lhm.put(c, lhm.getOrDefault(c, 0) + 1);
        }
 
        // Iterate using java 8 forEach method
        lhm.forEach(
            (k, v) -> System.out.print(k + " " + v));
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "neveropen";
        int n = str.length();
 
        printCharWithFreq(str, n);
    }
}


Output: 

g2 e4 k2 s2 f1 o1 r1

 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32337 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6706 POSTS0 COMMENTS
Nicole Veronica
11870 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11934 POSTS0 COMMENTS
Shaida Kate Naidoo
6821 POSTS0 COMMENTS
Ted Musemwa
7086 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6778 POSTS0 COMMENTS