How to sort an ArrayList using multiple sorting criteria?

If you (almost) always want to use that order you can add the Comparable interface to Quote and implement a compareTo method.

 public int compareTo(Quote quote) {
     int result = this.getName().compareTo(quote.getName());
     if (result == 0) {
        result = this.getChange().compareTo(quote.getChange());
     }
     if (result == 0) {
        result = this.getPercentChange().compareTo(quote.getPercentChange());
     }
     return result;
 }

Then use a sorted collection, or sort a list, and the quotes will be sorted.

For ad hoc sorting, a separate, possibly anonymous, Comparator is better.

Leave a Comment