Share on Google+Share on Google+

Display non-duplicate words from file

Advertisement
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

Advertisements

Advertisement

Posted on: December 6, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.