You can use the 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
The TreeSet
does not allow duplicated values, being great for storing letters without repetition. So a Map
is filled with the value counted by the method frequency
.
See working on Ideone.com.
Observing: Note that your method counts uppercase, lowercase and accented as different letters. If you want accounts for occurrences that ignore accents, uppercase and lowercase, 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 main
from before):
!:1 A:3 B:1 E:2 I:1 N:1 O:2 R:1 S:3 T:2 V:1
You want to count repeated letters in a sentence and then show the result?
– novic
Related question: How to count the number of occurrences of a String in a Jsonarray?
– Sorack