简体   繁体   中英

How can I preserve order with an EnumMap in java

I have an EnumMap that I'm using and I will need to keep the order of the items that I'm passing in. I know that when using a HashMap, I can initialize a LinkedHashMap in order to preserve order like so:

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

However, I'd like to use an EnumMap instead. How would I be able to do something like this:

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

As the API tells us:

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

This means it is internally sorted and simply not supposed to be ordered differently, eg insertion order as you need it.

You really don't need an EnumMap . You can get away with just using the LinkedHashMap , but you have to be mindful of what you're keying off of.

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

This will:

  • Use a LinkedHashMap
  • Ensure insertion order relative to when the key (and its values) are added

Some possibilities:

  • Use LinkedHashMap and construct an EnumMap from it each time you need one.
  • As biziclop suggested in a comment, extend EnumMap .
  • I was going to suggest extending or modifying ContentType to contain mutable static ordering information, which would be horribly hacky but maybe okay for testing. But I like the above two ideas better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM