LearnFrenzy
Sign in Take a free test

File Handling, IO and NIO · File Handling Programs · Question 10

Letter frequency histogram from a file in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links