Java EnumMap Methods Example

In this source code example, we will show you the usage of important Java EnumMap class methods with examples.

EnumMap is a specialized Map implementation for use with enum type keys. It's part of the java.util package. Being both compact and efficient, the performance of EnumMap surpasses HashMap when the key is an enum type.

Common Operations with EnumMap in Java

import java.util.EnumMap;

// Define an enumeration for colors
enum Color {
    RED, GREEN, BLUE
}

public class EnumMapDemo {
    public static void main(String[] args) {
        // 1. Initializing an empty EnumMap
        EnumMap<Color, String> colorMap = new EnumMap<>(Color.class);

        // 2. Putting values into EnumMap
        colorMap.put(Color.RED, "Apple");
        colorMap.put(Color.GREEN, "Leaf");
        colorMap.put(Color.BLUE, "Sky");
        System.out.println("Color map: " + colorMap);

        // 3. Retrieving a value
        String blueItem = colorMap.get(Color.BLUE);
        System.out.println("Item associated with BLUE: " + blueItem);

        // 4. Checking if a specific key is present
        boolean hasRed = colorMap.containsKey(Color.RED);
        System.out.println("Map contains RED key: " + hasRed);

        // 5. Checking if a specific value is present
        boolean hasApple = colorMap.containsValue("Apple");
        System.out.println("Map contains 'Apple' value: " + hasApple);

        // 6. Removing a key-value pair
        colorMap.remove(Color.GREEN);
        System.out.println("After removing GREEN key: " + colorMap);

        // 7. Getting the size of the map
        int size = colorMap.size();
        System.out.println("Size of color map: " + size);
    }
}

Output:

Color map: {RED=Apple, GREEN=Leaf, BLUE=Sky}
Item associated with BLUE: Sky
Map contains RED key: true
Map contains 'Apple' value: true
After removing GREEN key: {RED=Apple, BLUE=Sky}
Size of color map: 2

Explanation:

1. Initializing an empty EnumMap that will have Color enum keys.

2. put: Adding key-value pairs to the map using the put method.

3. get: Retrieving the value associated with a specific key.

4. containsKey: Checking if a specific key is present in the map.

5. containsValue: Checking if a specific value is present in the map.

6. remove: Removing a specific key-value pair based on the key.

7. size: Getting the number of key-value pairs present in the map.

EnumMap is a specialized map implementation for use with enumeration type keys. It's compact and efficient, ensuring operations like get or put are faster than their HashMap counterparts when using enum keys.


Comments