javadictionaryenumsenum-map

What is better to iterate over an EnumMap in java?


Suppose I have declared an enum and corresponding emummap as:

enum MyEnum {
    CONSTANT1, CONSTANT2, CONSTANT3;
}

EnumMap<MyEnum, String> MyEnumMap = new EnumMap<MyEnum, String>(MyEnum.class);

I want to iterate over MyEnumMap, for example, just to print each Entry one by one.

What is the best approach(fastest) to iterate over keys in the following cases:

  1. When it is ensured that each constant in MyEnum is a key in MyEnumMap
  2. When each constant in MyEnum may or may not be a key in MyEnumMap

I want to choose between foreach loop using MyEnumMap.keySet() or MyEnum.values(). Any other approach is most welcomed.


Solution

  • If you take a look at code of EnumMap#keySet()

    381  public Set<K> keySet() {
    382 Set<K> ks = keySet;
    383 if (ks != null)
    384 return ks;
    385 else
    386 return keySet = new KeySet();
    387 }

    you will notice that it returns keySet used internally by EnumMap to store keys.

    Now each time we call MyEnum.values() we are getting different array filled with all enum elements. This means that first empty array is created which later needs to be filled with all enums which requires some iteration.

    So in first approach you are skipping iterating over enums already stored by map, while insecond approach we simply creating some temporary array which involves additional iteration over all MyEnum elements.