Search code examples
javasortingcollectionscomparecompareto

Custom Java sort by name


I want to sort something like this:

Given an ArrayList of objects with name Strings, I am trying to write the compareTo function such that Special T is always first, Special R is always second, Special C is always third, and then everything else is just alphabetical:

Special T
Special R
Special C
Aaron
Alan
Bob
Dave
Ron
Tom

Is there a standard way of writing this kind of compare function without needing to iterate over all possible combinations between the special cases and then invoking return getName().compareTo(otherObject).getName()); if it's a non-special case?


Solution

  • I would put the special cases in a HashMap<String, Integer> with the name as key and position as value. The advantages are:

    1. search is in O(1) order of magnitude
    2. The HashMap may be populated from an external source