How to preserve order using EnumMap in java

I have an EnumMap that I am using and I will need to maintain the order of the elements that I am passing. I know that when using HashMap, I can initialize the LinkedHashMap to keep this order

HashMap<String, List<String>> contentTypeToIdList = new LinkedHashMap<String, List<String>>();

      

However, I would like to use EnumMap. How could I do something like this:

EnumMap<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<ContentType, List<String>>();

      

+3


source to share


3 answers


As the API says:

Enum maps are stored in the natural order of their keys (the order in which the enumeration constants are declared). This is reflected in the iterators returned by the collection views (keySet (), entrySet (), and values ​​()).



This means it is internally sorted and just doesn't have to be ordered differently, for example. the order of insertion when you need it.

+1


source


You don't really need it EnumMap

. You can get away by just using LinkedHashMap

, but you have to remember what you are disconnecting.

Map<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<>();

      



It will be:

  • Use LinkedHashMap

  • Ensure insertion order regarding when the key is added (and its values)
+1


source


Some possibilities:

  • Use LinkedHashMap

    and constructEnumMap

    from it whenever you need it.
  • As biziclop says in comment add EnumMap

    .
  • I was going to suggest expanding or modifying ContentType

    to contain volatile static ordering information that would be terribly hacky, but perhaps perfectly acceptable for testing. But I like these two ideas better.
0


source







All Articles