Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting: How to create a particular custom order, then alphabetic sort in java

I have an Enum with around 70 fields.

I want 10 of them to be displayed in a particular order, then I want the rest to be displayed alphabetically using a Comparator. I have tried many things, but I can't get it to work.

Here is a sample enum with reduces attributes I want Picard, Worf and William to display first, then the rest alphabetically

I cannot use any third libraries. It must be java core. So if you want to provide guava answers, or apache commons answer, please do so in addition to java core.

public enum StarTrek {

    JeanLucPicard("Picard"),
    GeordiLaForge("Geordi"),
    DiannaTroi("Dianna"),
    Worf("Worf"),
    WilliamRiker("William"),
    Q("Q");

    private String label;

    StarTrek(String label) { this.label = label; }

    @Override public String toString() { return label; }
}

    List<StarTrek> specificOrder = Arrays.asList(StarTrek.JeanLucPicard, StarTrek.Worf, StarTrek.WilliamRiker);

    Comparator<StarTrek> comp = new Comparator<StarTrek>() {
            @Override
            public int compare(StarTrek o1, StarTrek o2) {
                //TODO: loop through the specific order, and display those first, then for the rest, go alphabetic
                return 0;
            }
    };

    List<StarTrek> all = Arrays.asList(StarTrek.values());
    Collections.sort(all, comp);
like image 682
Shervin Asgari Avatar asked Feb 26 '13 14:02

Shervin Asgari


People also ask

How do you sort data in alphabetical order in Java?

Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.

What is custom sorting in Java?

In order to sort Employee object on different criteria, we need to create multiple comparators e.g. NameComparator, AgeComparator, and SalaryComparator, this is known as custom sorting in Java. This is different from the natural ordering of objects, provided by the compareTo() method of java. lang.

How do you sort a list of objects based on an attribute of the objects in Java?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.


1 Answers

It is bad design to place additional data in your enum just for the purposes of displaying in a particular order. Instead, place all that logic in your Comparator, as shown below:

public class StarTrekSorter implements Comparator<StarTrek> {

  private static final List<StarTrek> ORDERED_ENTRIES = Arrays.asList(
      StarTrek.JeanLucPicard, StarTrek.Worf, StarTrek.WilliamRiker);

  @Override
  public int compare(StarTrek o1, StarTrek o2) {
    if (ORDERED_ENTRIES.contains(o1) && ORDERED_ENTRIES.contains(o2)) {
      // Both objects are in our ordered list. Compare them by
      // their position in the list
      return ORDERED_ENTRIES.indexOf(o1) - ORDERED_ENTRIES.indexOf(o2);
    }

    if (ORDERED_ENTRIES.contains(o1)) {
      // o1 is in the ordered list, but o2 isn't. o1 is smaller (i.e. first)
      return -1;
    }

    if (ORDERED_ENTRIES.contains(o2)) {
      // o2 is in the ordered list, but o1 isn't. o2 is smaller (i.e. first)
      return 1;
    }

    return o1.toString().compareTo(o2.toString());
  }
}

Now, you can just sort:

public static void main(String[] args) {

  List<StarTrek> cast = Arrays.asList(StarTrek.values());

  Collections.sort(cast, new StarTrekSorter());

  for (StarTrek trek : cast) {
    System.out.println(trek);
  }  
}

which prints

Picard
Worf
William
Dianna
Geordi
Q
like image 197
Duncan Jones Avatar answered Jan 01 '23 12:01

Duncan Jones