Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to count occurence of each letter in String in Java

I am not able to get the correct occurrence of each letter present in the string. What is wrong with my code?

Code:

public class consecutiveCharacters {
    public static String solve(String A, int B) {
        HashMap<String, Integer> map = new HashMap<>();
        for (int i=0;i<A.length();i++) {
            Integer value = map.get(A.charAt(i));
            if(value == null){
                map.put(String.valueOf(A.charAt(i)),1);
            }
            else {
                map.put(String.valueOf(A.charAt(i)),i+1);
            }
        }
        System.out.println(map); 
        String text = "i feel good";
        return text;
    }

    public static void main(String[] args) {
        solve("aabbccd",2);
    }
}

The output of the map should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{a=2, b=2, c=2, d=1}

Yet the output that the above code is giving is:

{a=1, b=1, c=1, d=1}

>Solution :

Using Map.merge() you can rid of checking this yourself:

Map<Character, Integer> map = new HashMap<>();
for( char c : A.toCharArray()) {
    map.merge(c, 1, Integer::sum);                      
}

merge() takes 3 parameters:

  • A key which is the character in your case
  • A value to put for the key, which is 1 in your case
  • A merge bi-function to combine the new and existing values if the entry already existed. Integer::sum refers to Integer's method static int sum(int a, int b) which basically is the same as your value + 1.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading