EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. It belongs to the java.util package.
Few important features of EnumMap are as follows:
- EnumMap class is a member of the Java Collections Framework & is not synchronized.
- EnumMap is an ordered collection and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constant are declared inside enum type )
It’s a high-performance map implementation, much faster than HashMap. - All keys of each EnumMap instance must be keys of a single enum type.
- EnumMap doesn’t allow null key and throws NullPointerException when we attempt to insert the null key.
- Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.
- EnumMap is internally represented as arrays. This representation is extremely compact and efficient.
Declaration:
public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable
K – key object type
V – value object type
K must extend Enum, which enforces the requirement that the keys must be of the specified enum type.
EnumMap Hierarchy
EnumMap-in-Java
Constructors of EnumMap
1. EnumMap(Class keyType): The constructor is used to create an empty EnumMap with the specified keyType.
EnumMap<K, V> em = new EnumMap<K, V>(Class keyType);
2. EnumMap(EnumMap m): The constructor is used to create an enum map with the same keyType as the specified enum map, with initial mappings being the same as the EnumMap
EnumMap<K, V> em = new EnumMap<K, V>(EnumMap m);
3. EnumMap(Map m): The constructor is used to create an enum map with initialization from the specified map in the parameter.
EnumMap<K, V> em = new EnumMap<K, V>(Map m);
Example:
/ Java program to illustrate working
// of EnumMap and its functions.
import java.util.EnumMap;
public class EnumMapExample
{
public enum PAI
{
CODE, CONTRIBUTE, QUIZ, MCQ;
}
public static void main(String args[])
{
// Java EnumMap
// Creating EnumMap in java with key
// as enum type STATE
EnumMap<PAI, String> paiMap = new
EnumMap<PAI, String>(PAI.class);
// Java EnumMap Example 2:
// Putting values inside EnumMap in Java
// Inserting Enum keys different from
// their natural order
paiMap.put(PAI.CODE, "Start Coding with pai");
paiMap.put(PAI.CONTRIBUTE, "Contribute for others");
paiMap.put(PAI.QUIZ, "Practice Quizes");
paiMap.put(PAI.MCQ, "Test Speed with Mcqs");
// Printing size of EnumMap in java
System.out.println("Size of EnumMap in java: " +
paiMap.size());
// Printing Java EnumMap
// Print EnumMap in natural order
// of enum keys (order on which they are declared)
System.out.println("EnumMap: " + paiMap);
// Retrieving value from EnumMap in java
System.out.println("Key : " + PAI.CODE +" Value: "
+ paiMap.get(PAI.CODE));
// Checking if EnumMap contains a particular key
System.out.println("Does paiMap has "+PAI.CONTRIBUTE+": "
+ paiMap.containsKey(PAI.CONTRIBUTE));
// Checking if EnumMap contains a particular value
System.out.println("Does paiMap has :" + PAI.QUIZ + " : "
+ paiMap.containsValue("Practice Quizes"));
System.out.println("Does paiMap has :" + PAI.QUIZ + " : "
+ paiMap.containsValue(null));
}
}
Output
Size of EnumMap in java: 4
EnumMap: {CODE=Start Coding with pai, CONTRIBUTE=Contribute for others, QUIZ=Practice Quizes, MCQ=Test Speed with Mcqs}
Key : CODE Value: Start Coding with pai
Does paiMap has CONTRIBUTE: true
Does paiMap has :QUIZ : true
Does paiMap has :QUIZ : false
Basic Operations on EnumMap
1. Adding Elements
To add elements to the EnumMap, we can use put() or putAll() methods of it. The code below shows how to use them.
// Java program to add elements
// to the EnumMap
import java.util.EnumMap;
class AddingElementsToEnumMap {
enum Color {
RED, GREEN, BLUE, WHITE
}
public static void main(String[] args)
{
// Creating an EnumMap of the Color enum
EnumMap<Color, Integer> colors1 = new EnumMap<>(Color.class);
// Insert using put() method
colors1.put(Color.RED, 1);
colors1.put(Color.GREEN, 2);
// print mappings to the console
System.out.println("EnumMap colors1: " + colors1);
// Creating an EnumMap of the Color Enum
EnumMap<Color, Integer> colors2 = new EnumMap<>(Color.class);
// Add using the putAll() Method
colors2.putAll(colors1);
colors2.put(Color.BLUE, 3);
// print mappings to the console
System.out.println("EnumMap colors2: " + colors2);
}
}
Output
EnumMap colors1: {RED=1, GREEN=2}
EnumMap colors2: {RED=1, GREEN=2, BLUE=3}
2. Accessing the Elements
We can access the elements of EnumMap using entrySet(), keySet(), values(), get(). The example below explains these methods.
// Java program to access the
// elements of EnuMap
import java.util.EnumMap;
class AccessElementsOfEnumMap {
enum Color {
RED, GREEN, BLUE, WHITE
}
public static void main(String[] args) {
// Creating an EnumMap of the Color enum
EnumMap<Color, Integer> colors = new EnumMap<>(Color.class);
colors.put(Color.RED, 1);
colors.put(Color.GREEN, 2);
colors.put(Color.BLUE, 3);
colors.put(Color.WHITE, 4);
System.out.println("EnumMap colors : " + colors);
// Using the entrySet() Method
System.out.println("Key/Value mappings: " + colors.entrySet());
// Using the keySet() Method
System.out.println("Keys: " + colors.keySet());
// Using the values() Method
System.out.println("Values: " + colors.values());
// Using the get() method
System.out.println("Value of RED : " + colors.get(Color.RED));
}
}
Output
EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}
Key/Value mappings: [RED=1, GREEN=2, BLUE=3, WHITE=4]
Keys: [RED, GREEN, BLUE, WHITE]
Values: [1, 2, 3, 4]
Value of RED : 1
3. Remove Elements
To remove the elements EnumMap provides two variations of the remove() method. The code below explains that.
// Java program to remove the
// elements of EnumMap
import java.util.EnumMap;
class Main {
enum Color {
RED, GREEN, BLUE, WHITE
}
public static void main(String[] args) {
// Creating an EnumMap of the Color enum
EnumMap<Color, Integer> colors = new EnumMap<>(Color.class);
colors.put(Color.RED, 1);
colors.put(Color.GREEN, 2);
colors.put(Color.BLUE, 3);
colors.put(Color.WHITE, 4);
System.out.println("EnumMap colors : " + colors);
// Remove a mapping using the remove() Method
int value = colors.remove(Color.WHITE);
System.out.println("Removed Value: " + value);
boolean result = colors.remove(Color.RED, 1);
System.out.println("Is the entry {RED=1} removed? " + result);
// print the updated map to the console
System.out.println("Updated EnumMap: " + colors);
}
}
Output
EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}
Removed Value: 4
Is the entry {RED=1} removed? true
Updated EnumMap: {GREEN=2, BLUE=3}
4. Replace Elements
Map interface provides three variations of the replace() method to change the mappings of EnumMap. They are explained in the below example code.
// Java program to replace
// elements of EnumMap
import java.util.EnumMap;
class Main {
enum Color {
RED, GREEN, BLUE, WHITE
}
public static void main(String[] args) {
// Creating an EnumMap of the Color enum
EnumMap<Color, Integer> colors = new EnumMap<>(Color.class);
colors.put(Color.RED, 1);
colors.put(Color.GREEN, 2);
colors.put(Color.BLUE, 3);
colors.put(Color.WHITE, 4);
System.out.println("EnumMap colors " + colors);
// Using the replace() Method
colors.replace(Color.RED, 11);
colors.replace(Color.GREEN, 2, 12);
System.out.println("EnumMap using replace(): " + colors);
// Using the replaceAll() Method
colors.replaceAll((key, oldValue) -> oldValue + 3);
System.out.println("EnumMap using replaceAll(): " + colors);
}
}
Output
EnumMap colors {RED=1, GREEN=2, BLUE=3, WHITE=4}
EnumMap using replace(): {RED=11, GREEN=12, BLUE=3, WHITE=4}
EnumMap using replaceAll(): {RED=14, GREEN=15, BLUE=6, WHITE=7}
Synchronized EnumMap:
The implementation of an EnumMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the Collections.synchronizedMap(java.util.Map<K, V>) method. This is best done at the creation time, to prevent accidental unsynchronized access.
Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap<EnumKey, V>(…));
Methods of EnumMap
K – type of the key object
V – type of the value object
- clear() Removes all mappings from this map.
- clone() Returns a shallow copy of this enum map.
- containsKey(Object key) Returns true if this map contains a mapping for the specified key.
- containsValue(Object value) Returns true if this map maps one or more keys to the specified value.
- entrySet() Returns a Set view of the mappings contained in this map.
- equals(Object o) Compares the specified object with this map for equality.
- get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
- hashCode() Returns the hash code value for this map.
- keySet() Returns a Set view of the keys contained in this map.
- put(K key, V value) Associates the specified value with the specified key in this map.
- putAll(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map.
- remove(Object key) Removes the mapping for this key from this map if present.
- size() Returns the number of key-value mappings in this map.
- values() Returns a Collection view of the values contained in this map.
Methods declared in class java.util.AbstractMap
- isEmpty() Returns true if this map contains no key-value mappings.
- toString() Returns a string representation of this map.
Methods declared in interface java.util.Map
- compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Attempts to compute a
- mapping for the specified key and its current mapped value (or null if there is no current mapping).
- computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
- computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
- forEach(BiConsumer<? super K,? super V> action) Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
- getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
- merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
- putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
- remove(Object key, Object value) Removes the entry for the specified key only if it is currently mapped to the specified value.
- replace(K key, V value) Replaces the entry for the specified key only if it is currently mapped to some value.
- replace(K key, V oldValue, V newValue) Replaces the entry for the specified key only if currently mapped to the specified value.
- replaceAll(BiFunction<? super K,? super V,? extends V> function) Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
EnumSet vs EnumMap
- Internal Representation EnumMap is internally represented as arrays. The representation is compact and
- efficient. EnumSet internally represented as BitVector or sequence of bits.
- Permits Null Elements? Null keys are not allowed but Null values are allowed. Null elements are not permitted.
Is the Abstract Class? No Yes - Instantiation Since EnumMap is not an abstract class, it can be instantiated using the new operator. It is an abstract class, it does not have a constructor. Enum set is created using its predefined methods like allOf(), noneOf(), of(), etc.
- Implementation EnumMap is a specialized Map implementation for use with enum type keys. EnumSet is a specialized Set implementation for use with enum types.