BenParker93 BenParker93 - 2 years ago 172
Java Question

How to Sort ArrayList of Objects by a field without Comparator / Comparable

I have an arraylist of objects which cannot implement the Comparator / Comparable interface.

The objects have a field : 'SequenceNumber' which is an integer. I need to sort the arraylist in order of this field (lowest to highest) without implementing the mentioned interfaces.

Is there an easy way to do this, I can manually write a sorting algorithm but wondering if there is a more efficient (and more bug-free) way of doing this which I have missed while searching?

Note : Using Java 7.

Answer Source

Create a comparator class to handle sorting:

private class MyObjectComparator<MyObject> implements Comparator<MyObject> {

  /**
   * {@inheritDoc}
   */
  @Override
  public int compare(MyObject o1, MyObject o2) {
     return o2.getSequenceNumber() - o1.getSequenceNumber();
  }

}

Then sort your ArrayList with it:

Collections.sort(myArrayList, new MyObjectComparator());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download