Comparing Long values using Collections.sort(object)

Toran Billups picture Toran Billups · May 30, 2011 · Viewed 47.5k times · Source

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

Answer

Rob Hoff picture Rob Hoff · Oct 20, 2014

Long.compare( x , y )

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.

public class MyObject implements Comparable<MyObject>
{
  public long id;

  @Override
  public int compareTo(MyObject obj) {
    return Long.compare(this.id, obj.id);
  }
}

Call Collections.sort(my_objects) where my_objects is something like

  List<MyObject> my_objects = new ArrayList<MyObject>();
  // + some code to populate your list