Java EnumSet and EnumMap made simple
source link: https://www.mastertheboss.com/java/java-enumset-and-enummap-made-simple/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
The EnumMap
and EnumSet
are specialized implementations in Java that are optimized for working with Enum keys and Enum values, respectively. In this article we will learn how to use them and which are the common use cases. Finally, we will also highlight the differences with the standard Map and Set objects.
Overview to Java Enums
Firstly, let’s provide some background on the concept of Enums. In Java you can declare Enums using the enum
keyword. They consist of a fixed set of named constants, also known as enum constants. You typically define enums in uppercase letters and represent a specific type of object.
public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
EnumSetOverview
An EnumSet
is a specialized Set
implementation in Java designed to work with enums.
- It is highly optimized to handle enums efficiently and is used for storing a set of enum constants.
- Provides constant-time performance for the basic operations (addition, removal, contains) and is very memory efficient.
- Ideal for working with enums when the requirement is to perform set operations (like union, intersection) efficiently.
Here is an example of EnumSet:
EnumSet<DayOfWeek> weekdays = EnumSet.range(DayOfWeek.MONDAY, DayOfWeek.FRIDAY);
EnumMap Overview
An EnumMap
is a specialized Map
implementation in Java that works with enums as keys.
- It’s internally represented as an array, making it highly efficient in terms of performance and memory usage.
- Specifically designed to work with enums as keys, offering constant-time performance for key-related operations.
- Often used when you need a mapping of enum constants to values, providing a structured way to associate values with specific enum constants.
Here is an example of EnumMap:
EnumMap<DayOfWeek, String> dayMessages = new EnumMap<>(DayOfWeek.class); dayMessages.put(DayOfWeek.MONDAY, "Have a great start!");
A complete example
Next, we will show a full example which combines all the concepts discussed so far. This Java class demonstrates the use of EnumSet
to create sets of DayOfWeek
enum constants (weekend
and weekdays
) and EnumMap
to associate messages with each day of the week (dayMessages
). The program prints out the sets of days and their associated messages using these data structures.
import java.util.EnumSet; import java.util.EnumMap; enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public class EnumSetEnumMapExample { public static void main(String[] args) { // Using EnumSet EnumSet<DayOfWeek> weekend = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY); EnumSet<DayOfWeek> weekdays = EnumSet.complementOf(weekend); System.out.println("Weekend days: " + weekend); System.out.println("Weekdays: " + weekdays); // Using EnumMap EnumMap<DayOfWeek, String> dayMessages = new EnumMap<>(DayOfWeek.class); dayMessages.put(DayOfWeek.MONDAY, "Have a great start!"); dayMessages.put(DayOfWeek.TUESDAY, "Keep going!"); dayMessages.put(DayOfWeek.WEDNESDAY, "Halfway there!"); dayMessages.put(DayOfWeek.THURSDAY, "Almost done!"); dayMessages.put(DayOfWeek.FRIDAY, "Weekend is near!"); dayMessages.put(DayOfWeek.SATURDAY, "Enjoy your weekend!"); dayMessages.put(DayOfWeek.SUNDAY, "Relax and recharge!"); // Displaying messages for each day using EnumMap for (DayOfWeek day : DayOfWeek.values()) { System.out.println(day + ": " + dayMessages.get(day)); } } }
Run the above example and verify it prints the messages for each day:
Comparing Enums Maps and EnumSets
The following tables compare the differences between the EnumMap
and EnumSet
type:
EnumSet
Maintain a collection of unique enum constants, offering efficient set operations.
Typically implemented using bit vectors or similar efficient structures, providing fast set operations
Supports set operations like union, intersection, complement, etc., typically used for set-related functionalities.
EnumMap
Used as a mapping structure, associating values with enum constants in a key-value pair format.
Internally uses arrays to store key-value pairs, optimized for enum keys.
Allows operations associated with maps, such as put, get, containsKey, etc., mainly used for key-value mappings.
Convert EnumMap to Map and EnumSet to List
Finally, we will provide some examples to convert the Enu types into the corresponding Java Collections Set and Map.
Firstly, here is how to convert EnumSet to List
EnumSet<Color> colorEnumSet = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE); // Convert EnumSet to List List<Color> colorList = new ArrayList<>(colorEnumSet);
Then, here is how to convert the EnumMap to a Java Map:
// Create an EnumMap of DayOfWeek with String values EnumMap<DayOfWeek, String> dayMessages = new EnumMap<>(DayOfWeek.class); dayMessages.put(DayOfWeek.MONDAY, "Have a great start!"); dayMessages.put(DayOfWeek.TUESDAY, "Keep going!"); // Convert EnumMap to HashMap Map<DayOfWeek, String> hashMapFromEnumMap = new HashMap<>(dayMessages);
Conclusion
This tutorial provided an overview of Java Enums and discusses the specific use cases and differences between EnumSet and EnumMap, showcasing their distinct functionalities and optimal use cases when working with enums in Java.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK