I want to create an ordered set, or list, and add enums to the collection so they are inserted in enum order.
Can I do this without creating an explicit comparator? Is there a collection that will use the inherent order of the enum to maintain the order in the collection?
Example in Groovy of what I want to do (I expect it will be similar for Java with a for loop instead of a closure):
TreeSet<TransactionElement> elements = new TreeSet<TransactionElement>()
elementList.each{ element -> elements.add(element)}
TransactionElement is an enum and the elements should be added to the TreeSet in the order they are listed in the enum
UPDATE:
Solution I went with:
EnumSet<TransactionElement> elements = EnumSet.noneOf(TransactionElement.class);
elementList.each{ element -> elements.add(element)}
Some great examples of how to use EnumSet and EnumMap here
If you want a
Setofenumvalues, thenEnumSetis probably your best bet. Not only is it more efficient that using a non-specializedSet, it also guarantees that the iteration will work in the natural order of theenum.