java: TreeSet order

You can use one of the TreeSet constructors: http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#TreeSet%28java.util.Comparator%29

This allows you to specify your own comparator that allows you to organize the entries in the Set however you like.

Implement a Comparator that extracts the number from the String and then sorts by the number first, only falling back to a String comparison if both numbers are equal.


The TreeSet implementation is sorting by the lexicographic order of the string values you insert. If you want to sort by the integer value, then you'll need to do as these others suggested and create a new object and override the compareTo method, or use your own comparator.

Set<String> set = new TreeSet<String>(new Comparator<String>() {

    public int compare(String one, String other) {
        // implement
    }

});

or

public class MyClass implements Comparable {
    private String key;
    private int value;

    public int compareTo(MyClass other) {
        // implement
    }

    public boolean equals(MyClass other) {
        // implement
    }

    // snip ...
}

Set<MyClass> set = new TreeSet<MyClass>();

Tags:

Java

Treeset