Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preserve order with an EnumMap in java

Tags:

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>>();
like image 858
DanielD Avatar asked Jun 05 '17 21:06

DanielD


People also ask

Does EnumMap maintain order?

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() ).

How do you keep an insertion order on a map?

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.

Is order maintained in HashMap?

HashMap does not maintains insertion order in java. Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java.

Does Java map preserve order?

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.


Video Answer


2 Answers

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.

like image 111
s1m0nw1 Avatar answered Nov 02 '22 05:11

s1m0nw1


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
like image 27
Makoto Avatar answered Nov 02 '22 03:11

Makoto