Sorting collection in Java

Ref:
http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property
http://stackoverflow.com/questions/18441846/how-sort-a-arraylist-in-java

Code:


// This is your list
List<MyObject> myObjects= new ArrayList<MyObject>();
// add some items to this list ...

// This is how to sort this list
Collections.sort(myObjects, new Comparator<MyObject>() {
  @Override
  public int compare(MyObject obj1,MyObject obj2) {
    // add compare logic, and return result, for example:
    return obj1.propertyToCompare.compareTo(obj2.propertyToCompare);
  }
});

Leave a comment