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>>();
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 class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.
HashMap does not maintains insertion order in java. Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java.
HashMap is unordered per the second line of the documentation: This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
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, e.g. 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:
LinkedHashMap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With