I am trying to read lines of input from a BufferedReader and output them in sorted order without any duplicate lines. I think that using a TreeSet would be my best option. Unfortunately I don't know how to get my input from the BufferedReader into the TreeSet.

This is what I have tried:

    public static void doIt(BufferedReader r, PrintWriter w) throws IOException {

        SortedSet<String>  ts = new TreeSet<String>();
        //make arrayList of bufferedReader Strings, add TreeSet, print 
        String[] lines;
        for(String line : lines){
            ts.add(line);
            w.println(line);
        }

This clearly doesn't work, but I'm at a loss for what to do to make it work? I am new to programming so any help would be greatly appreciated!

Recommended Answers

All 5 Replies

how to get my input from the BufferedReader

Look at the BufferedReader class for a method that will return a String when a line is read from the file. Then you can add that String to the TreeSet

Thank you so much! All of the documentation is a little overwhelming and often ends up confusing me before I find the proper method to use.

Do you have questons about any of the methods? If so, copy the doc for the methods and ask questions about what you don't understand.

Which method(s) return Strings?

Also look at using the Scanner class to read lines from the file. It may be easier for you to use.

I'm pretty sure I want the method readLine(). To add this line to the TreeSet does ts.add(r.readline()) work? Or does this statement not make any sense? Or should it be in several statements?

It should be in several statements,
You should read the String into a variable first so you can check it BEFORE using it with the add() method. For example, you will want to test for the end of file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.