How can I use a custom `Comparator` to define a specific sort order in Java?

I want to sort a list of cars by color, but not in alphabetical order. Instead, I need a java custom comparator that ensures colors appear in a predefined sequence (e.g., Red first, then Blue, etc.). How can I implement this while keeping sorting efficient?

From my experience, the cleanest and most efficient way to define a specific order is by using a Map to assign priorities. It’s a classic move when working with a java custom comparator.

Here’s how I usually do it:

Map<String, Integer> colorOrder = Map.of("Red", 1, "Blue", 2, "Green", 3);
cars.sort(Comparator.comparingInt(car -> colorOrder.getOrDefault(car.color, Integer.MAX_VALUE)));

:white_check_mark: Why I prefer this?

You get constant-time lookups (O(1)), your logic stays clean, and it scales well with more items.

Right on, @macy-davis! I’ve used that Map-based approach a lot too. But sometimes, when I want something simpler or more human-readable—especially in smaller use cases—I go for a List with indexOf.

It still works within the realm of a java custom comparator, but it trades off a bit of performance for clarity:

List<String> colorOrder = List.of("Red", "Blue", "Green");
cars.sort(Comparator.comparingInt(car -> colorOrder.indexOf(car.color)));

:white_check_mark: Why?

Super easy to update the order later, and the intent is visually obvious, which helps when sharing code across teams.

Jumping in here—both those approaches are solid! But if you’re aiming for flexibility without pulling in additional data structures like a separate Map or List, you can directly define the logic inside the compare() method. It’s still part of building a java custom comparator, just more embedded:

cars.sort((c1, c2) -> {
    List<String> order = List.of("Red", "Blue", "Green");
    return Integer.compare(order.indexOf(c1.color), order.indexOf(c2.color));
});

:white_check_mark: Why? You avoid maintaining an external reference and keep everything tightly scoped—great for one-off custom sort logic inside modules.