Java Data Type How to - Order enum values








Question

We would like to know how to order enum values.

Answer

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/* w ww.j a va 2 s  .c om*/
public class Main {
    public static void main(String[] args) {
        List<Value> list = Arrays.asList(Value.values());
        System.out.println(list);
        
        Collections.sort(list, (Value o1, Value o2) -> o1.getValue1() - o2.getValue1());
        System.out.println(list);
        Collections.sort(list, (Value o1, Value o2) ->o1.getValue2() - o2.getValue2());
        System.out.println(list);
    }
}
enum Value {
  A(1, 2), B(5, 1), C(3, 0);
  private int value1;
  private int value2;

  private Value(int value1, int value2) {
      this.value1 = value1;
      this.value2 = value2;
  }

  public int getValue1() {
      return value1;
  }

  public int getValue2() {
      return value2;
  }
}

The code above generates the following result.