>>106706315
in plain Java, it's just
public static Map<Character, Integer> countLetters(String s) {
Map<Character, Integer> result = new TreeMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
result.put(c, result.getOrDefault(c, 0) + 1);
}
return result;
}
in Enterprise Java, it's just
public class LetterFrequencyCounter {
private final String input;
public LetterFrequencyCounter(String input) {
this.input = input;
}
public TreeMap<Character, Integer> countLetters() {
TreeMap<Character, Integer> charIndices = buildCharIndexMap();
int[] counts = countCharacterOccurrences(charIndices);
return buildResultMap(charIndices, counts);
}
private TreeMap<Character, Integer> buildCharIndexMap() {
TreeMap<Character, Integer> charIndices = new TreeMap<>();
int counter = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (!charIndices.containsKey(c)) {
charIndices.put(c, counter++);
}
}
return charIndices;
}
private int[] countCharacterOccurrences(TreeMap<Character, Integer> charIndices) {
int[] counts = new int[charIndices.size()];
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
int index = charIndices.get(c);
counts[index]++;
}
return counts;
}
private TreeMap<Character, Integer> buildResultMap(TreeMap<Character, Integer> charIndices, int[] counts) {
TreeMap<Character, Integer> result = new TreeMap<>();
for (Map.Entry<Character, Integer> entry : charIndices.entrySet()) {
result.put(entry.getKey(), counts[entry.getValue()]);
}
return result;
}
}