Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

public enum ActorType {

  ARTIST(1),
  PRODUCER(2),
  MIXER(3);

  private final int priority;

  ActorType(int priority) {
    this.priority = priority;
  }

  public static int compare(ActorType t1, ActorType t2) {
    return Integer.compare(t1.priority, t2.priority);
  }
}

Then the comparator is quite simple.

public class ActorByActorTypeComparator implements Comparator<Actor> {

  @Override
  public int compare(Actor actor1, Actor actor2) {
    return ActorType.compare(actor1.getActorType(), actor2.getActorType());
  }
}

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.

public class ActorByTypeComparator implements Comparator<Actor> {
  
  private final Map<String, Integer> typePriorityMap = new HashMap<>();
  //add each type in map
  //map.put("Artist", 1);
  //or provide the map from constructor

  @Override
  public int compare(Actor a1, Actor a2) {
    int a1Priority = this.typePriorityMap.getOrDefault(a1.getType(), Integer.MAX_VALUE);
    //handle unknown type, according to your needs
    int a2Priority = this.typePriorityMap.getOrDefault(a2.getType(), Integer.MAX_VALUE);
    return Integer.compare(a1Priority, a2Priority);
  }
}

The first option is cleaner and less error prone.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading