-1

the code below is counting character. I am a bit new to hashmaps so I am confused about the syntax and what's it doing from this line: Map charCounter = new TreeMap(); Can someone please dumb this code down and explain from that line please?

    public class repeated {
    public static void main(String[] args) {

        String str = "Abaa";

        char[] char_array = str.toCharArray();

        System.out.println("The Given String is : " + str);

    Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();

        for (char x : char_array) {

    charCounter.put(x,charCounter.get(x) == null ? 1 : charCounter.get(x) + 1);

        }

    for (Character key : charCounter.keySet()) {
  System.out.println("occurrence of '" + key + "' is  "+ charCounter.get(key));
        }

    }

}
guylifestyle
  • 317
  • 1
  • 6
  • 13

1 Answers1

0

TreeMap is one of the classes that implement the Map interface. Therefore you can assign an instance of TreeMap to a variable whose type is Map.

The line charCounter.put(x,charCounter.get(x) == null ? 1 : charCounter.get(x) + 1) searches the char x in the Map. If it's not found, it adds it as a key to the map with value of 1. If it's found it gets its current value from the Map and increases it by one.

This means this Map counts how many times each character appears in the input String.

Eran
  • 387,369
  • 54
  • 702
  • 768