Java Program to Implement EnumMap API
Last Updated :
07 Jan, 2021
EnumMap is a Map implementation that has enum values as its keys. Now, you all may be wondering what is enum, right? Well, enum is a user-defined data type that is generally used when all possible values are already known.
In this article, we'll be implementing EnumMap API in a java program. But first, we'll be learning some of the concepts that have been used in the program and then we'll dive right into the program.
The EnumMap API belongs to java.util package. For implementing the EnumMap API a special class is to be used, which is defined below.
EnumMapImpl<K extends Enum<K>, V> class
This class represents the use of EnumMap API for enum or enumerated data types. K stands for a key type entry and V stands for a value type entry in the map.
Example 1:
Let us consider an EnumMap with dress sizes as its keys.
enum Dress_sizes
{
extra-small, small, medium, large, extra-large;
}
Now, for say, we implement a basic feature of EnumMap API, we would like to know if a particular dress size is available or not, for this, we would use the function. enumMap.containsKey(), which would return true if the size is present else would return false.
Declaration:
enumMap.containsKey(Dress_sizes.extra-large);
Input: extra-large
Output: true
Input: extra-extra-large
Output: false
As the size extra-large was present in the Map, it returned true and as the size extra-extra-large wasn't present, it returned false.
Example 2:
Let's take another such example, implementing another basic feature of the Map, for say we want to empty the above EnumMap. For this, we'll simply use enumMap.clear() function which would clear the EnumMap.
Declaration:
enumMap.clear();
Output: The enumMap is now empty.
enum Dress_sizes
{
}
Approach used for implementation:
- An EnumMap class has been defined and the enum values and the key sets are pre-defined.
- In the main function, the values have been paired with their individual key sets.
- Basic enumMap functions are then used to perform various tasks.
Implementation:
Java
// Java program to implement enum Map API
import java.lang.*;
import java.util.Collection;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class EnumMapImpl<K extends Enum<K>, V> {
EnumMap<K, V> enumMap;
// For creating an empty enum map with the specified key
// type.
public EnumMapImpl(Class<K> keyType)
{
enumMap = new EnumMap<K, V>(keyType);
}
// For creating an enum map which will have the same key
// type as the specified enum map,
public EnumMapImpl(EnumMap<K, ? extends V> m)
{
enumMap = new EnumMap<K, V>(m);
}
// For Creating an enum map that is initialized from the
// specified map.
public EnumMapImpl(Map<K, ? extends V> m)
{
enumMap = new EnumMap<K, V>(m);
}
// Clears the Mappings from the enumMap.
public void clear() { enumMap.clear(); }
// Returns true if the specified value is found.
public boolean containsValue(Object value)
{
return enumMap.containsValue(value);
}
// Returns true if the specified key is found.
public boolean containsKey(Object key)
{
return enumMap.containsKey(key);
}
// Returns the key set of the enumMap
public Set<K> keySet() { return enumMap.keySet(); }
// Returns the entry set( values + keys) of the enumMap.
public Set<Map.Entry<K, V> > entrySet()
{
return enumMap.entrySet();
}
// Returns the value to which a specified key is mapped,
// else returns null if the specified key is not found.
public V get(Object key) { return enumMap.get(key); }
// Associates the specified Key and Value.
public V put(K key, V value)
{
return enumMap.put(key, value);
}
// Copies the mappings of another map to the specified
// map.
public void putAll(Map<? extends K, ? extends V> map)
{
enumMap.putAll(map);
}
// Returns the size of the enumMap.
public int size() { return enumMap.size(); }
// Returns the values mapped in the specified enumMap.
public Collection<V> values()
{
return enumMap.values();
}
// Returns true if the enumMap is empty.
public boolean isEmpty() { return enumMap.isEmpty(); }
// Initializing the enumMap.
enum Week_Days {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
// Main function.
public static void main(String[] args)
{
EnumMapImpl<Week_Days, Integer> enumMap
= new EnumMapImpl<Week_Days, Integer>(Week_Days.class);
enumMap.put(Week_Days.SUNDAY, 1);
enumMap.put(Week_Days.MONDAY, 2);
enumMap.put(Week_Days.TUESDAY, 3);
enumMap.put(Week_Days.WEDNESDAY, 4);
enumMap.put(Week_Days.THURSDAY, 5);
enumMap.put(Week_Days.FRIDAY, 6);
enumMap.put(Week_Days.SATURDAY, 7);
System.out.println("The size of the enumMap is: "
+ enumMap.size());
System.out.println();
System.out.println("The values of the enumMap is: ");
Collection<Integer> ci = enumMap.values();
Iterator<Integer> iin1 = ci.iterator();
while (iin1.hasNext())
{
System.out.print(iin1.next() + "\t");
}
System.out.println();
System.out.println();
System.out.println("The key set of the enumMap is: ");
Set<Week_Days> ws = enumMap.keySet();
Iterator<Week_Days> iin2 = ws.iterator();
while (iin2.hasNext())
{
System.out.print(iin2.next() + " ");
}
System.out.println();
System.out.println();
System.out.println("The enumMap is: ");
Iterator<Entry<Week_Days, Integer> > week_iterator;
Set<Entry<Week_Days, Integer> > wi = enumMap.entrySet();
week_iterator = wi.iterator();
while (week_iterator.hasNext())
{
System.out.println(week_iterator.next() + "\t");
}
System.out.println();
System.out.println("The enumMap contains Key SUNDAY "
+ ": " + enumMap.containsKey(Week_Days.SUNDAY));
System.out.println("The enumMap contains Value 1 "
+ ": "
+ enumMap.containsValue(1));
enumMap.clear();
if (enumMap.isEmpty())
System.out.println("The EnumMap is now empty.");
else
System.out.println("The EnumMap is not empty.");
}
}
OutputThe size of the enumMap is: 7
The values of the enumMap is:
1 2 3 4 5 6 7
The key set of the enumMap is:
SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
The enumMap is:
SUNDAY=1
MONDAY=2
TUESDAY=3
WEDNESDAY=4
THURSDAY=5
FRIDAY=6
SATURDAY=7
The enumMap contains Key SUNDAY : true
The enumMap contains Value 1 : true
The EnumMap is now empty.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read