I'm trying to sort a simple list of objects by a long - the below isn't working because one of the long strings is pushed to the top simply because it starts with a lower number. So I'm looking for a way to sort these by the actual long values directly
The current obj implementation looks something like the below. In the class I'm using this I call Collections.sort(trees);
public class Tree implements Comparable<Tree> {
public String dist; //value is actually Long
public int compareTo(Tree o) {
return this.dist.compareTo(o.dist);
}
}
Just an example I made for sorting Files by date using a Long comparator:
Why not
It depends on how you want to do things? Do you want to keep the current implementation of Comparable? If yes, use the sort method which takes a Comparator and implement a custom comparator which uses the actual "long" values of the string (
Long.parseLong(dist)
). If no, then just modify the currentcompareTo
and use the Long values of the "dist".BTW, I'd revisit the logic and ask myself why "dist" is of type String when it is actually a Long?
If you have an object that you want to sort on a long value, and it implements Comparable, in Java 7+ you can use
Long.compare(long x, long y)
(which returns an int)E.g.
Call
Collections.sort(my_objects)
where my_objects is something likewhy not actually store a long in there:
that or first compare the length of the strings and then compare them
well if the dist variable is actually long then you might try using