Java Data Type How to - Customize sort of Enum value








Question

We would like to know how to customize sort of Enum value.

Answer

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*from  w w w  .ja  v a 2s .c o m*/
public class Main {
  public static void main(String[] args) {
    sortDates(Arrays.asList(new DAY[] { DAY.MON, DAY.WED, DAY.TUE, DAY.THU,
        DAY.SUN, DAY.SAT }));
  }

  public static void sortDates(List<DAY> dayList) {
    Collections.sort(dayList, new Comparator<DAY>() {
      public int compare(DAY day1, DAY day2) {
        return day1.getWeight() - day2.getWeight();
      }
    });
    System.out.println("sortedlist is" + dayList.toString());
  }
}

enum DAY {
  MON("MONDAY", 2), TUE("TUESDAY", 3), WED("WEDNESDAY", 4), THU("THURSDAY", 5), FRI(
      "FRIDAY", 6), SAT("SATURDAY", 7), SUN("SUNDAY", 1);
  private String m_name = "";
  private int m_weight;

  DAY(String name, int weight) {
    m_name = name;
    m_weight = weight;
  }

  public int getWeight() {
    return this.m_weight;
  }
}

The code above generates the following result.