I have a text file and I was curious about what character appears how often in the text.
Any review is appreciated.
public class CountLetters {
public static void main(String[] args) throws Exception {
TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();
File file = new File("C:/text.txt");
Scanner scanner = new Scanner(file,"utf-8");
while (scanner.hasNext()) {
char[] chars = scanner.nextLine().toLowerCase().toCharArray();
for (Character c : chars) {
if(!Character.isLetter(c)){
continue;
}
else if (hashMap.containsKey(c)) {
hashMap.put(c, hashMap.get(c) + 1);
} else {
hashMap.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
The output will be for example:
a: 1202 b: 311 c: 603 d: 510 e: 2125 f: 373 g: 362 h: 718 i: 1313 j: 5 k: 74 l: 678 m: 332 n: 1129 o: 1173 p: 348 q: 40 r: 812 s: 1304 t: 1893 u: 415 v: 195 w: 314 x: 86 y: 209 z: 9