Write a sentence to a file, read it character by character with a buffered Reader, count each letter (ignoring case), and print a histogram of the five most common letters.
Solution
Main.java
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws IOException {
Path f = Files.createTempFile("pangram", ".txt");
Files.writeString(f, "Pack my box with five dozen liquor jugs, and see Java read every letter!");
Map<Character, Integer> freq = new TreeMap<>();
try (Reader r = Files.newBufferedReader(f)) {
int c;
while ((c = r.read()) != -1) {
char ch = Character.toLowerCase((char) c);
if (Character.isLetter(ch)) freq.merge(ch, 1, Integer::sum);
}
}
freq.entrySet().stream()
.sorted(Map.Entry.<Character, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
.limit(5)
.forEach(e -> System.out.println(e.getKey() + " " + "#".repeat(e.getValue()) + " " + e.getValue()));
System.out.println(freq.size() + " distinct letters");
Files.delete(f);
}
}
Output Verified by compiling and running
e ######### 9
a ##### 5
r #### 4
d ### 3
i ### 3
26 distinct letters
read() returns an int; it is cast to char only after checking for -1. The sentence is a pangram, so all 26 letters appear.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!