GTU OOP Program - 25
25). Write a program that reads words from a text file and displays all the nonduplicate words in descending order.The text file is passed as a command-line argument.
- import java.io.*;
- import java.util.*;
- class Program_25 {
- public static void main(String[] args) throws Exception {
- File fin = new File(args[0]);
- BufferedReader br = new BufferedReader(new FileReader(fin));
- StringBuffer buffer = new StringBuffer();
- String str;
- while ((str = br.readLine()) != null) { // reading the text file
- buffer.append(str); // storing text in StringBuffer
- buffer.append(" "); // Separating words by spaces
- }
- ArrayList list = new ArrayList(); // Declaring ArrayList
- StringTokenizer st = new StringTokenizer(buffer.toString().toLowerCase());
- while (st.hasMoreTokens()) { // creating a list of words
- String s = st.nextToken();
- list.add(s);
- }
- HashSet set = new HashSet(list); // it is created to avoid duplicate
- List arrayList = new ArrayList(set); // creating list of words
- Comparator c = Collections.reverseOrder();
- Collections.sort(arrayList, c);
- for (Object obj : arrayList) {
- System.out.println(obj.toString()); // displaying content
- }
- }
- }
Input.txt file
Output
Comments