C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Example file: file.txt
aaaa
bbbbb
aaaa
bbbbb
aaaa bbbbb
CCcc
xx
y y y y y
Z
On each char: We test to see if we have a space—we avoid hashing spaces. We then put the char in the HashMap.
HashMapGetOrDefault: We call this method to get an existing value from the HashMap or 0. Then we put one plus that value.
Finally: We use a for-loop on the result of keySet(). We display all characters found and their frequencies in the file.
ForJava program that uses HashMap
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class Program {
public static void main(String[] args) throws IOException {
HashMap<Integer, Integer> hash = new HashMap<>();
// Load this text file.
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\programs\\file.txt"));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c != ' ') {
// Increment existing value in HashMap.
// ... Start with zero if no key exists.
int value = hash.getOrDefault((int) c, 0);
hash.put((int) c, value + 1);
}
}
}
// Close object.
reader.close();
// Display values of all keys.
for (int key : hash.keySet()) {
System.out.println((char) key + ": " + hash.get(key));
}
}
}
Output
a: 12
b: 15
C: 2
c: 2
x: 2
y: 5
Z: 1