简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM