What is EnumMap in Java?
EnumMap is one of the specialized implementation of Map interface for use with enum type keys, introduced in Java 1.5 with enumeration type. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient. Programmer often use HashMap to store enum type, because they are unaware about this little gem.
Enum constants are unique and have predefined length, you can't create new enum at runtime. It allows java designer to make highly optimized EmumMap. Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared).
Here is the topic that will cover in this post.
Java EnumMap class Declaration
EnumMap extends AbstractMap and implements Map. It is specifically for use with keys of an enum type. It is a generic class that has this declaration:
public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> implements java.io.Serializable, Cloneable
Here, K specifies the type of keys, and V specifies the type of values. Notice that E must extend Enum<E>, which enforces the requirement that the elements must be of the specified enum type.
Java EnumMap features
- Java EnumMap inherits
AbstractMap
class.- All keys of each EnumMap instance must be keys of a single enum type.
- Java EnumMap does not permits
null
key, but permits multiplenull
values.- Enum maps are maintained in the natural order of their keys as the order in which the enum constants are declared).
- 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.
- Java EnumMap is not synchronized.
- Java EnumMap is not thread-safe. You can make thread-safe by doing
Map m = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...));- Java EnumMap implementation provides constant-time performance for the basic operations (like get, and put).
- Java EnumMap performance is better than HashMap.
Java EnumMap constructors
Java EnumMap have three constructors.
Constructor | Description |
---|---|
public EnumMap(Class<K> keyType) | Creates an empty enum map with the specified key type. |
public EnumMap(EnumMap<K, ? extends V> m) | Creates an enum map with the same key type as the specified enum map, initially containing the same mappings (if any). |
public EnumMap(Map<K, ? extends V> m) | Creates an enum map initialized from the specified map. If the
specified map is an EnumMap instance, this constructor behaves
identically to EnumMap(EnumMap). Otherwise, the specified map
must contain at least one mapping (in order to determine the new
enum map's key type).
|
Below code snippet show example to create EnumMap instances using it's constructors.
enum Color { RED, GREEN, BLUE; } EnumMap<Color, String> enumMap1 = new EnumMap<Color, String>(Color.class); enumMap1.put(Color.RED, "red"); enumMap1.put(Color.GREEN, "green"); EnumMap<Color, String> enumMap2 = new EnumMap<Color, String>(enumMap1); enumMap2.put(Color.BLUE, "blue"); Map<Color, String> hashMap= new HashMap<>(); hashMap.put(Color.RED, "red"); EnumMap<Color,String> enumMap3 = new EnumMap<Color, String>(hashMap);
Java EnumMap methods
Method | Description |
---|---|
public int size() | Returns the number of key-value mappings in this map. |
public V get(Object key) | Returns the value to which the specified key is mapped,
or null if this map contains no mapping for the key.
|
public boolean containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
public V put(K key, V value) | Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced. |
public void putAll(Map<? extends K, ? extends V> m) | Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map. |
public V remove(Object key) | Removes the mapping for the specified key from this map if present,
otherwise null if there was no mapping for key |
public void clear() | Removes all of the mappings from this map. The map will be empty after this call returns. |
public boolean containsValue(Object value) | Returns true if this map maps one or more keys to the specified value. |
public Set<K> keySet() | Returns a Set view of the keys contained in this map. |
public Collection<V> values() | Returns a Collection view of the values contained in this map. |
public Set<Map.Entry<K,V>> entrySet() | Returns a Set view of the mappings contained in this map. |
public boolean equals(Object o) | Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings, as specified in the Map.equals(Object) contract. |
public int hashCode() | Returns the hash code value for this map. The hash code of a map is defined to be the sum of the hash codes of each entry in the map. |
public EnumMap<K, V> clone() | Returns a shallow copy of this enum map. The values themselves are not cloned. |
Example
Here is a simple program of EnumMap.
package com.walking.techie; import java.util.EnumMap; public class EnumMapDemo { enum Color { RED, GREEN, BLUE; } public static void main(String[] args) { EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class); enumMap.put(Color.RED, "red"); enumMap.put(Color.GREEN, "green"); enumMap.put(Color.BLUE, "blue"); System.out.println("All key-value in enum map : " + enumMap); System.out.println("Size of the enum map is : " + enumMap.size()); System.out.println("Getting value for key = " + Color.RED + " is : " + enumMap.get(Color.RED)); // checking if EnumMap contains a particular key System.out.println("Does enum map has :" + Color.GREEN + " " + enumMap.containsKey(Color.GREEN)); // checking if EnumMap contains a particular value System.out.println("Does enum map has blue value: " + enumMap.containsValue("blue")); System.out.println("Does enum map has white value: " + enumMap.containsValue("white")); System.out.println("Removing key = " + Color.RED + " from enum map and value is : " + enumMap .remove(Color.RED)); System.out.println("All key-value in enum map : " + enumMap); } }
Output of above program is shown below:
All key-value in enum map : {RED=red, GREEN=green, BLUE=blue} Size of the enum map is : 3 Getting value for key = RED is : red Does enum map has :GREEN true Does enum map has blue value: true Does enum map has white value: false Removing key = RED from enum map and value is : red All key-value in enum map : {GREEN=green, BLUE=blue}
Iterate or Traverse over EnumMap
1. Iterating EnumMap in java using iterator and KeySet
package com.walking.techie; import java.util.EnumMap; import java.util.Iterator; import java.util.Set; public class EnumMapTraversal { enum Color { RED, GREEN, BLUE; } public static void main(String[] args) { EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class); enumMap.put(Color.RED, "red"); enumMap.put(Color.GREEN, "green"); enumMap.put(Color.BLUE, "blue"); // Returns a Set view of the keys contained in this map. Set<Color> set = enumMap.keySet(); // Returns an iterator over the elements in this set. Iterator<Color> itr = set.iterator(); while (itr.hasNext()) { Color key = itr.next(); System.out.println("Key=" + key + " Value=" + enumMap.get(key)); } } }
Output of above program is shown below:
Key=RED Value=red Key=GREEN Value=green Key=BLUE Value=blue
2. Iterating EnumMap in java using EntrySet and Java Iterator
package com.walking.techie; import java.util.EnumMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class EnumMapTraversal { enum Color { RED, GREEN, BLUE; } public static void main(String[] args) { EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class); enumMap.put(Color.RED, "red"); enumMap.put(Color.GREEN, "green"); enumMap.put(Color.BLUE, "blue"); // Returns a Set view of the mappings contained in this map. Set<Entry<Color, String>> entry = enumMap.entrySet(); // Returns an iterator over the elements in this set. Iterator<Entry<Color, String>> iterator = entry.iterator(); while (iterator.hasNext()) { Map.Entry<Color, String> entry2 = iterator.next(); System.out.println("Key=" + entry2.getKey() + " Value=" + entry2.getValue()); } } }
Output of above program is shown below:
Key=RED Value=red Key=GREEN Value=green Key=BLUE Value=blue
3. Iterating EnumMap in java using EntrySet and Java for loop
package com.walking.techie; import java.util.EnumMap; import java.util.Map.Entry; import java.util.Set; public class EnumMapTraversal { enum Color { RED, GREEN, BLUE; } public static void main(String[] args) { EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class); enumMap.put(Color.RED, "red"); enumMap.put(Color.GREEN, "green"); enumMap.put(Color.BLUE, "blue"); Set<Entry<Color, String>> entrySet = enumMap.entrySet(); for (Entry<Color, String> entry : entrySet) { System.out.println("Key=" + entry.getKey() + " Value=" + entry.getValue()); } } }
Output of above program is shown below:
Key=RED Value=red Key=GREEN Value=green Key=BLUE Value=blue
4. Iterating EnumMap in java using KeySet and Java for loop
package com.walking.techie; import java.util.EnumMap; public class EnumMapTraversal { enum Color { RED, GREEN, BLUE; } public static void main(String[] args) { EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class); enumMap.put(Color.RED, "red"); enumMap.put(Color.GREEN, "green"); enumMap.put(Color.BLUE, "blue"); for (Color key : enumMap.keySet()) { System.out.println("Key=" + key + " Value=" + enumMap.get(key)); } } }
Output of above program is shown below:
Key=RED Value=red Key=GREEN Value=green Key=BLUE Value=blue
5. Iterating EnumMap in java using Java 8 forEach and lambda expression
package com.walking.techie; import java.util.EnumMap; public class EnumMapTraversal { enum Color { RED, GREEN, BLUE; } public static void main(String[] args) { EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class); enumMap.put(Color.RED, "red"); enumMap.put(Color.GREEN, "green"); enumMap.put(Color.BLUE, "blue"); // using java 8 for each and lambda expression enumMap.forEach((k, v) -> { System.out.println("Key=" + k + " Value=" + v); }); } }
Output of above program is shown below:
Key=RED Value=red Key=GREEN Value=green Key=BLUE Value=blue
factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
ReplyDeletefactorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.