Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: TreeSet order

Tags:

java

treeset

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 
like image 440
Enzo Avatar asked Apr 29 '14 12:04

Enzo


2 Answers

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>();
like image 152
jgitter Avatar answered Sep 20 '22 18:09

jgitter


Using lambda

Set<String> set = new TreeSet<String>(
                (o1, o2) -> String.format("%3s", o1.substring( o1.indexOf(" ") + 1)).replace(" ","0")
                .compareTo( String.format("%3s", o2.substring( o2.indexOf(" ") + 1)).replace(" ","0")
                                     ));
set.add("test 15");
set.add("dfd 2");
set.add("ersfd 20");
set.add("asdt 10");
set.stream().forEach(s -> System.out.println(s));

result:

dfd 2
asdt 10
test 15
ersfd 20

But I strongly recommend separe the significant values (in this case integers) in other key estucture. for easy manipulation.

like image 32
jalbertomr Avatar answered Sep 21 '22 18:09

jalbertomr