You can use Collections
of Java
in your favor as follows:
public static void main(String[] args) {
Map<String, Integer> ocorrencias;
ocorrencias = contar("Vê se tira notas boas!");
ocorrencias.forEach((chave, valor) -> System.out.print(chave + ":" + valor + " "));
}
private static Map<String, Integer> contar(String frase) {
Map<String, Integer> resultado = new TreeMap<>(); // TreeMap para manter o Map ordenado pelas chaves
List<String> ocorrencias;
Set<String> letras;
ocorrencias = Arrays.asList(frase.replace(" ", "").split("")); // Transforma a frase em uma lista que facilitará a contagem
letras = new TreeSet<>(ocorrencias); // Pega as letras sem duplicidade
// Percorre o array de letras sem repetição contando as ocorrências
letras.forEach((String letra) -> {
resultado.put(letra, Collections.frequency(ocorrencias, letra));
});
return resultado;
}
The code above produces:
!:1 V:1 a:3 b:1 e:1 i:1 n:1 o:2 r:1 s:3 t:2 ê:1
TreeSet
does not allow duplicate values, and is great for storing letters without repetition. Then a Map
is filled with the value counted by the frequency
method.
See working at Ideone.com .
Note: Note that your method is case-sensitive and accented as being different letters. If you want to account for occurrences by neglecting accents and case, use a method that performs conversions before counting as follows:
private static Map<String, Integer> contar2(String frase) {
String normalizado = Normalizer.normalize(frase, Normalizer.Form.NFD);
String semAcentos = normalizado.replaceAll("\p{InCombiningDiacriticalMarks}+", "");
frase = semAcentos.toUpperCase();
return contar(frase);
}
Which produces the following result (using the same% as before):
!:1 A:3 B:1 E:2 I:1 N:1 O:2 R:1 S:3 T:2 V:1