It's All Writing.

Writing makes you happy.

How to sort Objects by multiple fields at Apex

Environment

  • Apex

Premise

You can sort List of Objects with using sort method as below.

gist.github.com

In above example, shops is sorted by name ascending order ( Shop A, Shop B, Shop C). But what if you want to sort by multiple fields in Shop, not just by name?

Code

You can sort by multiple fields with using sort method as below. This example is just only different compareTo method.

gist.github.com

The sort condition is prioritized from the top line of the compareTo method ( priority order is category, proceeds, address ). For string type fields, you can switch between ascending and descending order by exchanging A and B with A.compareTo(B). For numeric type fields, you can switch between ascending and descending order by reversing the order of subtraction.