Skip to content
Advertisement

Complex logix in Java Comparator

I have a list of actors where each actor has a type (“Artist”, “Producer”, “Mixer”…some other types).

I need to order this list taking the following into consideration:

  1. Actors with the type of “Artist” will be displayed first.
  2. Actors with the type of “Producer” will be displayed next.
  3. Actors with the type of “Mixer” will be displayed next.

All actors also have to be ordered in alphabetical order based on their names.

I know I could write differet comparators and chain them, but I’m not sure how to implement the first 3 points.

Advertisement

Answer

The cleanest solution is use an enum for types, which holds the priority of each type. Basically maps the type to a priority number.

JavaScript

Then the comparator is quite simple.

JavaScript

If you use String for types and can’t change for whatever reason, one option is the comparator to hold the priority for each type. Something like this.

JavaScript

The first option is cleaner and less error prone.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement