EnumMap in Java10 Sept 2024 | 6 min read In the world of Java programming, data structures play a critical position in dealing with and organizing records correctly. One such facts structure that proves to be extremely beneficial is the EnumMap. EnumMaps are specialized Map implementations in Java designed to work with Enum keys. In this section, we will discuss EnumMap, exploring what they are, the way to use them efficaciously. What is an EnumMap?An EnumMap in Java is a high-overall performance implementation of the Map interface that makes use of Enum values as keys. It is a part of the java.util package and turned into introduced in Java 1.5. An EnumMap is mainly properly-suited for scenarios where the keys are constrained to a specific set of Enum values, as it affords a compact and efficient manner to save and get right of entry to records. One of the primary advantages of the use of EnumMap is that they're relatively specialized, that allows for quicker and extra efficient operations compared to standard-reason Map implementations like HashMap. EnumMap may be notion of as an array of values where the index of each cost corresponds to the ordinal value of an Enum key. This direct mapping makes EnumMap rather green for a wide range of use cases. Creating an EnumMapTo create an EnumMap, we need to specify the Enum elegance that defines the keys for the map. Let's keep in mind a simple example the use of an Enum to represent days of the week. EnumMapExample.java Output: {MONDAY=Work, TUESDAY=Gym, WEDNESDAY=Meetings, THURSDAY=Study, FRIDAY=Relax, SATURDAY=Family Time, SUNDAY=Chores} As we can see, the EnumMap continues the order of the Enum values and associates every value with a corresponding task. Accessing Values in an EnumMapAccessing values in an EnumMap is straightforward. We can use the get approach to retrieve the cost related to a selected Enum key. Here's an instance: EnumMapAccessExample.java Output: On WEDNESDAY, you should: Meetings In this example, we retrieve the pastime associated with Day.WEDNESDAY and display it inside the output. EnumMap vs. HashMapNow that we have a basic expertise of EnumMaps, you would possibly wonder how they examine to the more normally used HashMap. EnumMaps have numerous uses while operating with Enum keys:
While EnumMaps offer these advantages, it's critical to be aware that they're appropriate for unique use instances in which Enum keys are a natural suit. If your keys are not restricted to a restricted set of Enum values, a HashMap or another Map implementation is probably greater suitable. Iterating Over an EnumMapIterating over an EnumMap is just like iterating over other Map implementations. You can use the improved for loop or other strategies like entrySet to traverse the entries. EnumMapIterationExample.java Output: On MONDAY, you should: Work On TUESDAY, you should: Gym On WEDNESDAY, you should: Meetings On THURSDAY, you should: Study On FRIDAY, you should: Relax On SATURDAY, you should: Family Time On SUNDAY, you should: Chores In this example, we iterate over the EnumMap and print each entry that includes the Enum key (day of the week) and the associated activity. EnumMap provide numerous strategies for appearing numerous operations, such as adding, getting rid of, and checking the existing of key-value pairs. Some of the normally used methods consist of: put(Enum key, V value): Associates the required value with the desired Enum key in the EnumMap. Get(Enum key): Returns the price associated with the desired Enum key, or null if the important thing isn't always gift. remove(Enum key): Removes the key-cost pair related to the specified Enum key. ContainsKey(Enum key): Checks if the EnumMap contains the specified key. Size(): Returns the variety of key-value mappings inside the EnumMap. Let's study an example that demonstrates these methods: EnumMapMethodsExample.java Output: On WEDNESDAY, you should: Meetings Removed SATURDAY from the EnumMap. SUNDAY exists in the EnumMap: true Number of entries in the EnumMap: 6 In this example, we carry out numerous operations on the EnumMap, including retrieving, disposing of, checking the existence of, and counting entries. EnumMap Use CasesEnumMaps are great perfect for scenarios wherein you have a finite and acknowledged set of Enum keys and also we need to accomplice specific values with every key. Here are some common use instances for EnumMaps.
Performance ConsiderationsEnumMaps are designed for efficiency when working with Enum keys. They are typically faster and more memory-efficient than general-purpose Map implementations like HashMap for a limited and known set of keys. However, it's essential to be aware of their strengths and limitations: Iterating Order: EnumMaps hold the order of Enum values based on their ordinal positions. If we want a distinct ordering, we may want to do not forget an exclusive statistics shape. Null Values: EnumMaps do no longer allow null keys, and attempts to apply null as a key will result in a NullPointerException. In Summary, we have explored the sector of EnumMaps in Java, beginning from their basic principles and usage to extra advanced operations and use cases. EnumMaps are a specialized and efficient way to work with Enum keys and offer numerous uses in phrases of overall performance, type protection, and compactness. |
In computers, fundamental conversion (like decimal to binary or vice-versa) is an important task. In networking, it is important to understand IP addressing and subnetting. IP addressing is the main functionality of networking. For a network engineer, assigning IP addresses, determining the network or host ID...
3 min read
Image processing is a technique used to perform operations on an image to enhance it or extract useful information. One common task in image processing is converting a colored image to its negative. In this section, we will explore how to achieve this using Java. What...
4 min read
Our primary focus is on the set of vowels because the set of vowels is usually essential to many string manipulation problems, and one such problem is the problem of identifying the longest substring of the given string containing precisely K different vowels. The problem...
6 min read
A string inStr is given to us. The task is to compute the total number of unique substrings of the string inStr. All the characters of the input string are lowercase alphabets. Example 1: Input String inStr = "abcde" Output: There are 16 unique substrings. Explanation: The distinct substrings are: "",...
6 min read
Keywords are reserved words in Java that serve as a code key. These words can't be used for anything else because they're predefined. They can't be used as a variable name, object name, or any other identifier. There are 51 reserved terms or keywords in Java. List...
3 min read
In Java, Lock is an interface available in the Java.util.concurrent.locks package. Java lock acts as thread synchronization mechanisms that are similar to the synchronized blocks. After some time, a new locking mechanism was introduced. It is very flexible and provides more options in comparison to the...
5 min read
The fundamental units of object-oriented programming in Java are classes. They enable us to specify the composition and operation of objects. The static instance of a class is a key idea in Java. One instance of a class that is shared by all objects of that...
5 min read
In Java, conditional operators check the condition and decides the desired result on the basis of both conditions. In this section, we will discuss the conditional operator in Java. Types of Conditional Operator There are three types of the conditional operator in Java: Conditional AND Conditional OR Ternary Operator Operator Symbol Conditional or Logical...
3 min read
The DRY (Don't Repeat Yourself) approach is a way of thinking that helps programmers write cleaner, more manageable code. It goes beyond simple coding guidelines. When it comes to Java programming, DRY stands for Don't Repeat Yourself. It encourages programmers to write logic only once and...
4 min read
In multithreaded programming several threads are created and it is essential that at some points in their execution the threads have to be synchronized. CyclicBarrier of Java is one of the perfect solutions for a fixed number of threads which can come together at a particular...
5 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India