map counting with map

Solutions on MaxInterview for map counting with map by the best coders in the world

showing results for - "map counting with map"
Mathilda
25 Jan 2019
1// counting how many letters int the string
2String s = "alma mater";
3Map<Character, Integer> countOfLetters = new HashMap<>();
4for (char c: s.toCharArray()) {
5    if (countOfLetters.containsKey(c)) {
6        countOfLetters.put(c, countOfLetters.get(c) + 1);
7    }
8    else {
9        countOfLetters.put(c, 1);
10    }
11}
12System.out.println(countOfLetters); // { =1, a=3, r=1, t=1, e=1, l=1, m=2}
13int numberOfM = countOfLetters.get('m'); // 2