Software Development

Java – Sort an Enum type by its properties

This post shows how to sort an array or collection of Enum types in Java. We can use the natural sort order or sort by their properties. Any Enum type we create implements the Comparable interface. Below is an excerpt from the Java documentation.

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

Enum Type And Nature Order

Consider this Enum type with the following definition. We have three constants – HIGH, MEDIUM, and LOW. Each has a corresponding value for its level variable. Therefore, HIGH has 3, MEDIUM is 2, and LOW is 1.

If we are to sort by constants’ names in ascending order, Java will use their natural order. Therefore, we will get HIGH, MEDIUM, and LOW because H comes before M which comes before L. What if we want to sort the Enum constants by their  level properties? Read on.

Sorting Enum Constants To Their Natural Order

To demonstrate this default natural order for Enum constants, consider the following codes below. The codes use an array of Value and the Arrays.sort method. Without specifying additional parameters, we get HIGH, MEDIUM, and LOW, in that order.

This outputs:

Sort By Enum Type Properties

On the other hand, we may need to sort the Enum constant by their properties. In order words, we don’t rely on the natural order of the constants’ names. Consider the following codes. They are similar to the previous codes. However, we are using the Comparator interface to compare the level variables.

This outputs:

Sort Enum Type With Multiple Properties

In case we have an Enum type with multiple properties, we can still use the Comparator interface. This time, we chain together some of its methods. Consider the following codes – assuming we have the new gradeproperty.

Notice how we used the methods comparing and thenComparing methods.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like