Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treeset alphabetical sorting

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();
                }
            }
    }        
like image 629
A C Avatar asked Oct 28 '25 11:10

A C


1 Answers

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()

like image 161
emd Avatar answered Oct 30 '25 01:10

emd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!