This Java program is designed to analyze text files and count the occurrences of words, showcasing key concepts for novice programmers. It utilizes Java’s built-in classes, such as BufferedReader for reading input and PrintWriter for writing output. The program employs a TreeMap data structure to efficiently organize words alphabetically, and a custom class WordData to store information about each word, including its frequency count. The use of generics, demonstrated through TreeMap<String, WordData> and Comparator, ensures type safety and flexibility.
The program demonstrates sorting techniques by sorting a list of words based on their frequency count. Novice programmers can learn about basic file handling, data structures, generics, and sorting algorithms through this program, gaining foundational knowledge applicable to a wide range of Java applications.

Discover the mind behind the innovations – Elon Musk by Walter Isaacson, now on Audible. Dive into the life of a visionary shaping our future!
View on Amazon
The main functionalities of the program include:
- Input Reading: The program reads words from an input file using the
BufferedReader
class. It processes each word and ignores non-letter characters. - Data Representation: Tracks word occurrences by using a
TreeMap<String, WordData>
, whereWordData
is a custom class storing information about each word, including its frequency count. - Output Generation: Two distinct outputs are created. The first output displays words in alphabetical order, and the second output presents words ordered by the number of occurrences. This is achieved using the
PrintWriter
class. - Generic Programming Features: The program utilizes elements of Java’s generic programming framework, such as the use of
TreeMap
and sorting of a list of words with customComparators
. TheComparator
is now defined with generics to ensure type safety. - Error Handling: The program incorporates improved error handling mechanisms to address potential issues related to file input/output. Explicit closure of the
PrintWriter
is done to prevent premature closure and potential errors. - Modern File Handling: The outdated
TextReader
class has been replaced withBufferedReader
, and the program utilizes the try-with-resources statement for file handling to ensure proper resource closure.
Find Words Frequency in a Text File Java Program