Topics Index

EnumMapDemo - Java Example Program

import java.util.*;

class EnumMapDemo
    public static void main(String arg[])
        EnumMap map = new EnumMap<>(Numbers.class); // LINE A
        map.put(Numbers.One, 1);
        map.put(Numbers.Two, 2);
        map.put(Numbers.Three, 3);
        map.put(Numbers.Four, 4);
        map.put(Numbers.Five, 5);
        System.out.println(map); // LINE B
        Set set = map.keySet(); // Returns set view of keys // LINE C
        System.out.println(map.get(Numbers.Four)); // LINE D
        // to remove one object
        map.remove(Numbers.Four); // LINE E
        //calling set iterator
        Iterator it = set.iterator(); // LINE F
        //getting keys and values using iterator
        while (it.hasNext())
            Numbers n = (Numbers);
            System.out.println("Key = " + n + ", Value = " + map.get(n));

enum Numbers
    One, Two, Three, Four, Five;

{One=1, Two=2, Three=3, Four=4, Five=5}
[One, Two, Three, Four, Five]
{One=1, Two=2, Three=3, Five=5}
Key = One, Value = 1
Key = Two, Value = 2
Key = Three, Value = 3
Key = Five, Value = 5


In the above program we have demonstrated the working of EnumMap at LINE A we created a EnumMap and added elements of Numbers an enum class and displayed it at LINE B. At LINE C we are getting the set view of the keys in the EnumMap by keySet method. At LINE D we are getting the value of Four using get method. At LINE E we remove Four from the map using remove method and the modified map is displayed. At LINE F we are calling the set iterator method and using it we have displayed the keys and values in the EnumMap.

  • Try to add one more object SpecialDay with value 10 to the map. Use the below sample code.
    map.put("SpecialDay", 10);
    The above code will throw a runtime error since all the elements in an EnumMap must from a single enum class.
  • Check whether Four is still in the map.
    The output will be false since Four is removed from the map.
  • Remember EnumMap don't implement iterators hasPervious() and previous() methods

© meritcampus 2019

All Rights Reserved.

Open In App