In this article, we will learn all about EnumMap in Java. What is EnumMap and how to use it with examples?
What will we Learn?
- EnumMap Class Overview
- EnumMap Class Constructor Summary
- EnumMap Class Method Summary
- EnumMap Class Examples
1. EnumMap Class Overview
Like most collection implementations EnumMap is not synchronized. If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally.
Example:
Map<EnumKey, V> m
= Collections.synchronizedMap(new EnumMap<EnumKey, V>(...));
Properties of EnumMap Class
- All keys used in EnumMap must be from same Enum type which is specified while creating EnumMap in Java. For example, if you can not use different enum instances from two different enums.
- EnumMap is an ordered collection and they are maintained in the natural order of their keys( natural order of keys means the order on which enum constant are declared inside enum type ). you can verify this while Iterating over an EnumMap in Java.
- Iterators of EnumMap are fail-fast Iterator, much like of ConcurrentHashMap and doesn't throw ConcurrentModificationException and may not show an effect of any modification on EnumMap during Iteration process.
- You can not insert null keys inside EnumMap in Java. EnumMap doesn't allow null key and throws NullPointerException, at same time null values are permitted.
- EnumMap is not synchronized and it has to be synchronized manually before using it in a concurrent or multi-threaded environment. like synchronized Map, in Java, you can also make EnumMap synchronized by using Collections.synchronizedMap() method and as per Javadoc this should be done while creating EnumMap in java to avoid accidental non synchronized access.
- EnumMap likely gives a better performance than HashMap in Java. So prefer EnumMap if you are going to use enum keys.
2. EnumMap Class Constructor Summary
- EnumMap(Class keyType) - Creates an empty enum map with the specified key type.
- 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).
- EnumMap(Map<K,? extends V> m) - Creates an enum map initialized from the specified map.
3. EnumMap Class Method Summary
- void clear() - This method removes all mappings from this map.
- EnumMap<K,V> clone() - This method returns a shallow copy of this enum map.
- boolean containsKey(Object key) - This method returns true if this map contains a mapping for the specified key.
- boolean containsValue(Object value) - This method returns true if this map maps one or more keys to the specified value.
- Set<Map.Entry<K,V>> entrySet() - This method returns a Set view of the mappings contained in this map.
- boolean equals(Object o) - This method compares the specified object with this map for equality.
- V get(Object key) - This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
- int hashCode() - This method returns the hash code value for this map.
- Set keySet() - This method returns a Set view of the keys contained in this map.
- V put(K key, V value) - This method associates the specified value with the specified key in this map.
- void putAll(Map<? extends K,? extends V> m) - This method copies all of the mappings from the specified map to this map.
- V remove(Object key) - This method removes the mapping for this key from this map if present.
- int size() - This method returns the number of key-value mappings in this map.
- Collection values() - This method returns a Collection view of the values contained in this map.
4. EnumMap Class Examples
Simple Days Enum Example
In this example, we will use Days enum with all predefined days as keys in EnumMap:
import java.util.EnumMap;
import java.util.Map.Entry;
/**
* EnumMap Demonstration Example
* @author Ramesh Fadatare
*
*/
public class EnumMapExample {
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public static void main(final String[] args) {
final EnumMap<Days, String> enumMap = new EnumMap<>(Days.class);
enumMap.put(Days.SUNDAY, "Its Sunday!!");
enumMap.put(Days.MONDAY, "Its Monday!!");
enumMap.put(Days.TUESDAY, "Its Tuesday!!");
enumMap.put(Days.WEDNESDAY, "Its Wednesday!!");
enumMap.put(Days.THURSDAY, "Its Thursday!!");
enumMap.put(Days.FRIDAY, "Its Friday!!");
enumMap.put(Days.SATURDAY, "Its Saturday!!");
for(final Entry<Days, String> entry : enumMap.entrySet()){
System.out.println(" Key -> " + entry.getKey().SUNDAY);
System.out.println("Value - >" + entry.getValue());
}
}
}
Output:
Key -> SUNDAY
Value - >Its Sunday!!
Key -> SUNDAY
Value - >Its Monday!!
Key -> SUNDAY
Value - >Its Tuesday!!
Key -> SUNDAY
Value - >Its Wednesday!!
Key -> SUNDAY
Value - >Its Thursday!!
Key -> SUNDAY
Value - >Its Friday!!
Key -> SUNDAY
Value - >Its Saturday!!
Real world Example
As we know that every project has list status as a project is active, inactive, close, start etc. Let's create a ProjectStatus Enum which acts as key against each project. Let's demonstrate this with an example:
import java.util.EnumMap;
import java.util.Map.Entry;
/**
* EnumMap Demonstration Example
* @author Ramesh Fadatare
*
*/
public class EnumMapExample2 {
public static void main(final String[] args) {
final EnumMap<ProjectStatus, Project> enumMap = new EnumMap<>(ProjectStatus.class);
enumMap.put(ProjectStatus.ACTIVE, new Project(100, "Customer Management System", "Customer Management System"));
enumMap.put(ProjectStatus.INACTIVE,
new Project(200, "Employee Management System", "Employee Management System"));
for (final Entry<ProjectStatus, Project> entry : enumMap.entrySet()) {
final ProjectStatus projectStatus = entry.getKey();
System.out.println(" Key -> " + projectStatus.name());
final Project project = entry.getValue();
System.out.println("Value - >" + project.toString());
}
}
enum ProjectStatus {
ACTIVE, INACTIVE
}
}
class Project {
private int id;
private String name;
private String desc;
public Project(final int id, final String name, final String desc) {
super();
this.id = id;
this.name = name;
this.desc = desc;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(final String desc) {
this.desc = desc;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "[project id : " + this.id + ", project name : "
+ this.name + ", project desc : " + this.desc + " ]";
}
}
Output:
Key -> ACTIVE
Value - >[project id : 100, project name : Customer Management System, project desc : Customer Management System ]
Key -> INACTIVE
Value - >[project id : 200, project name : Employee Management System, project desc : Employee Management System ]
Related Collections Examples
- Java LinkedHashMap Example
- Java HashSet Example
- Java LinkedList Example
- Java ArrayList Example
- Java Comparator Interface Example
- Java Comparable Interface Example
- Java IdentityHashMap Example
- Java WeakHashMap Example
- Java EnumMap Example
- Java CopyOnWriteArraySet Example
- Java EnumSet Class Example
- Guide to Java 8 forEach Method
- Different Ways to Iterate over a List in Java [Snippet]
- Different Ways to Iterate over a Set in Java [Snippet]
- Different Ways to Iterate over a Map in Java [Snippet]
- Iterate over TreeSet in Java Example
- Iterate over LinkedHashSet in Java Example
- Remove First and Last Elements of LinkedList in Java
- Iterate over LinkedList using an Iterator in Java
- Search an Element in an ArrayList in Java
- Iterate over ArrayList using Iterator in Java
- Remove Element from HashSet in Java
- Iterating over a HashSet using Iterator
- How To Remove Duplicate Elements From ArrayList In Java?
- Different Ways to Iterate over List, Set, and Map in Java
- Java LinkedHashMap Example
- Java HashSet Example
- Java LinkedList Example
- Java ArrayList Example
- Java Comparator Interface Example
- Java Comparable Interface Example
- Java IdentityHashMap Example
- Java WeakHashMap Example
- Java EnumMap Example
- Java CopyOnWriteArraySet Example
- Java EnumSet Class Example
- Guide to Java 8 forEach Method
- Different Ways to Iterate over a List in Java [Snippet]
- Different Ways to Iterate over a Set in Java [Snippet]
- Different Ways to Iterate over a Map in Java [Snippet]
- Iterate over TreeSet in Java Example
- Iterate over LinkedHashSet in Java Example
- Remove First and Last Elements of LinkedList in Java
- Iterate over LinkedList using an Iterator in Java
- Search an Element in an ArrayList in Java
- Iterate over ArrayList using Iterator in Java
- Remove Element from HashSet in Java
- Iterating over a HashSet using Iterator
- How To Remove Duplicate Elements From ArrayList In Java?
- Different Ways to Iterate over List, Set, and Map in Java
This is not true "3. Iterators of EnumMap are fail-fast Iterator... " . Iterators are weakly consistent. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/EnumMap.html
ReplyDelete