Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum in ordered list or set

Tags:

java

enums

groovy

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

like image 209
Paul Avatar asked Aug 05 '26 23:08

Paul


2 Answers

If you want a Set of enum values, then EnumSet is probably your best bet. Not only is it more efficient that using a non-specialized Set, it also guarantees that the iteration will work in the natural order of the enum.

like image 54
Joachim Sauer Avatar answered Aug 08 '26 17:08

Joachim Sauer


Maybe you could tale a look at the EnumSet implementation.

like image 30
reef Avatar answered Aug 08 '26 16:08

reef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!