Home Tutorial Java Io Display non-duplicate words from file

 
 

Display non-duplicate words from file
Posted on: December 6, 2012 at 12:00 AM
In this tutorial, you will learn how to read a text file and display non-duplicate words in ascending order.

Display non-duplicate words from file

In this tutorial, you will learn how to read a text file and display non-duplicate words in ascending order. The given code reads the file and stored the file text into StringBuffer. The buffer object is then passed to StringTokenizer which broke the text of file into words. We have stored these words into ArrayList. ArrayList allows duplicate values therefore in order to get the non-duplicate words, we have converted ArrayList to HashSet as HashSet doest not allow duplicates. Then, again we have converted HashSet to ArrayList and using the Collection class, we have sorted the list elements which are actually the non-duplicate words.

data.txt:

Where there is a will 
there is a way.

Example:

import java.io.*;
import java.util.*;

class FileWords 
{
    public static void main(String[] args) throws Exception
    {        
        File f=new File("c:/data.txt");
        BufferedReader br=new BufferedReader(new FileReader(f));
        StringBuffer buffer=new StringBuffer();
        String str;
        while((str=br.readLine())!=null){
        buffer.append(str);
        buffer.append(" ");
        }
        ArrayList list=new ArrayList();
        StringTokenizer st = new StringTokenizer(buffer.toString().toLowerCase());
                while(st.hasMoreTokens()) {
                        String s = st.nextToken();
                        list.add(s);
                }
        HashSet set = new HashSet(list);
        List arrayList = new ArrayList(set);
        Collections.sort(arrayList);
        for (Object ob : arrayList)
        System.out.println(ob.toString());
    }
}

Output:

a
is
there
way.
where
will

Related Tags for Display non-duplicate words from file:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.