Sort enum

This example will show how to sort enums in specified order. A java enum type is a special data type that enables for a variable to be a set of predefined constants. Enums values are ordered in which they are declared. We could just change the order of the values and call ENUM.class.getEnumConstants() which will return the elements of an enum in the order which they are declared. But if other code is dependent on the ordinal value you would break it. By the way, Effective Java Item 31 suggests using instance fields instead of ordinals to represent constant values.

Order Enum Alphabetically

Lets for instance you want to use an Enum, in our case Fruit, to populate a drop down to display on a web page. It might look like this:

enum Fruit {
    ORANGE, APPLE, BANANAS, CHERRIES;
}

Using Guava Ordering class we can call Ordering.explicit which allows us order elements according to a specified order.

@Test
public void create_drop_down() {

    Ordering<Fruit> byFruitAlphabetical = Ordering.explicit(Fruit.APPLE,
            Fruit.BANANAS, Fruit.CHERRIES, Fruit.ORANGE);

    List<Fruit> dropDown = byFruitAlphabetical.sortedCopy(Arrays
            .asList(Fruit.values()));

    logger.info(dropDown);

    assertThat(
            dropDown,
            contains(Fruit.APPLE, Fruit.BANANAS, Fruit.CHERRIES,
                    Fruit.ORANGE));
}

Output

[APPLE, BANANAS, CHERRIES, ORANGE]

Sort list of enums

If we have a collection of Fruit we can sort an ArrayList of Enums in alphabetical order using the same technique above.

List<Fruit> RANDOM_FRUIT = Lists.newArrayList(Fruit.CHERRIES, Fruit.ORANGE,
        Fruit.APPLE, Fruit.CHERRIES, Fruit.BANANAS, Fruit.ORANGE);

@Test
public void sort_enum_with_guava() {

    Ordering<Fruit> byFruitAlphabetical = Ordering.explicit(Fruit.APPLE,
            Fruit.BANANAS, Fruit.CHERRIES, Fruit.ORANGE);

    List<Fruit> fruitAlphabetical = byFruitAlphabetical
            .sortedCopy(RANDOM_FRUIT);

    logger.info(fruitAlphabetical);

    assertThat(
            fruitAlphabetical,
            contains(Fruit.APPLE, Fruit.BANANAS, Fruit.CHERRIES,
                    Fruit.CHERRIES, Fruit.ORANGE, Fruit.ORANGE));

}

Output

[APPLE, BANANAS, CHERRIES, CHERRIES, ORANGE, ORANGE]