How do I get the treeset to sort alphabetically? And remove duplicates.. it's been driving me nuts for a day. Maybe I need to get some sleep..
public static void main(String[] args) {
        String fileName = args[0];
        String words;
        Scanner s = null;
        Iterator itr;
        try {
            s = new Scanner(new BufferedReader(new FileReader(fileName)));
                while (s.hasNext()) {
                    words = s.next();
                    TreeSet<String> ts = new TreeSet<String>();
                    ts.add(words);
                    System.out.println(ts);
                }
            } catch (FileNotFoundException fnfe) {
            System.exit(0);
        } finally {
               if (s != null) {
                   s.close();
                }
            }
    }        
TreeSet holds the set in a tree structure which is automatically sorted in natural order. Every class that implements the Comparable interface will be sorted. The String class implements the Comparable interface already so you don't have to do anything to sort it, just add it to the TreeSet.
Sets can't contain duplicates if the hashCode() and equals() methods are implemented how they should.
EDIT: The TreeSet<String> ts = new TreeSet<String>(); is located in the while() loop scope. You are initializing it every loop and loosing the data drom the previous one. Declare it outside the loop and don't use Collection.sort()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With