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
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>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With