Linked Hash Map counter not properly incrementing

Trying to "compress" a string by replacing duplicate characters with numbers (For example, the string aabcccccaaa would become a2blc5a3). I tried to use a Linked HashMap to solve the problem because the input order needs to be preserved, but the counter I created doesn’t seem to be incrementing properly. Any insight would be greatly appreciated.

public class StringCompression {
    public static void main(String[] args) {
        String s = "aabcccccaaa";
    public static String compString(String str) {
        LinkedHashMap <Character, Integer> alphabet = new LinkedHashMap<>();
        StringBuilder strbdr = new StringBuilder();     
        for(int i = 0; i < str.length(); i++) {
            if(alphabet.containsKey(str.charAt(i))) {
                alphabet.put(str.charAt(i), alphabet.get(str.charAt(i))+1);
            alphabet.put(str.charAt(i), 1);
//      System.out.println(alphabet.entrySet());
        for(var entry : alphabet.entrySet()) {
        return strbdr.toString();

>Solution :

Problem 1

The line alphabet.put(str.charAt(i), 1) keeps reseting each value to 1 , you need to put it in a else

for (int i = 0; i < str.length(); i++) {
    if (alphabet.containsKey(str.charAt(i))) {
        alphabet.put(str.charAt(i), alphabet.get(str.charAt(i)) + 1);
    } else {
        alphabet.put(str.charAt(i), 1);

Problem 2

First fix leads to a5b1c5 as maps have unique keys, so you can’t count the a at the beginning and the a at the end

Leave a Reply