Java – Sort an Enum type by its properties

Last Updated on

When we sort an array or collection of Enum types, the sort order is based on the natural order.

Enum<E> implements Comparable<E> via the natural order of the enum (the order in which the values are declared).

Sample Enum Type

Consider this Enum type with these codes:

The natural order for this is the order which the values are declared – HIGH, MEDIUM, and LOW. Therefore, HIGH comes before MEDIUM which comes before LOW.

Sorting Example

The following codes sorts an array of Value using the enum type’s natural order.

This outputs:

Sort By Enum Type Properties

To sort by properties, we need to override the natural order.

This outputs:

Karl San Gabriel

Karl San Gabriel

Professional Software Developer