java: TreeSet order

Enzo picture Enzo · Apr 29, 2014 · Viewed 37.2k times · Source

With this code I get this output:

 TreeSet<String> t=new TreeSet<String>();
  t.add("test 15");
  t.add("dfd 2");
  t.add("ersfd 20");
  t.add("asdt 10");


 Iterator<String> it=t.iterator();

 while(it.hasNext()){
   System.out.println(it.next);
 }

I get:

  asdt 10 
  dfd 2 
  ersfd 20 
  test 15

How can I get an order of this kind, based on the numbers, with TreeSet?

  dfd 2 
  asdt 10 
  test 15
  ersfd 20 

Answer

jgitter picture jgitter · Apr 29, 2014

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