Java › Enums

How would you implement a custom compareTo()-based ordering for an enum that differs from its natural declaration-order ordering, given Comparable's default implementation uses ordinal()?

Advanced

Answer

Since java.lang.Enum already implements Comparable using ordinal() (declaration order) and this implementation cannot be overridden (compareTo() in Enum is final), achieving a different sort order requires NOT relying on the enum's natural ordering at all -- instead, sort using an explicit external Comparator (via Comparator.comparing() referencing a field, or Comparator constructed from a defined priority mapping) passed to Collections.sort() or a stream's sorted() method, keeping the enum's own natural/declaration ordering untouched while still achieving the desired custom sort order for a specific use case.
enum Priority { LOW, MEDIUM, HIGH, CRITICAL }  // natural order: LOW < MEDIUM < HIGH < CRITICAL via ordinal

// Need CRITICAL first, LOW last for a specific report -- can't override compareTo(), so use an explicit Comparator
List<Priority> priorities = new ArrayList<>(List.of(Priority.values()));
priorities.sort(Comparator.comparing(Priority::ordinal).reversed());
// Or an entirely custom priority mapping via Comparator.comparing(p -> customPriorityMap.get(p))
Real-world example A ticket triage report needing CRITICAL-first ordering (opposite of the enum's natural LOW-to-CRITICAL declaration order used everywhere else in the codebase) sorts using an explicit reversed Comparator for just that one report, leaving the enum's own natural ordering (relied upon elsewhere for consistent default behavior) completely unaffected.

Common follow-ups: Why did the JDK designers make Enum's compareTo() final rather than allowing it to be overridden?;What's the risk of an enum's natural ordering silently changing if constants are reordered, given compareTo() is ordinal-based?