What is the EnumMap.toString() method in Java?

EnumMap is similar to Map, except that EnumMap only takes the Enum type as keys. Also, all the keys must be from a single enum type. For further details, refer here.

The toString() method returns the String representation of the EnumMap object.

Syntax

public String toString()

Parameters

This method doesn’t take any parameters.

Return value

  • The toString() method returns String as a result.
  • The returned string contains all the entries in the order returned by the map’s entrySet method.
  • The returned string is enclosed by open and close braces {}.
  • Each entry of the map is separated by a comma ,.
  • Each entry is in the format of key = value.
  • The key and value are converted to strings with the String.valueOf() method.

Code

import java.util.EnumMap;
class ToString {
enum Subject {
MATHS, SCIENCE, PROGRAMMING, ECONOMICS
};
public static void main( String args[] ) {
EnumMap<Subject, Integer> map = new EnumMap<>(Subject.class);
map.put(Subject.MATHS, 50);
map.put(Subject.SCIENCE, 60);
map.put(Subject.PROGRAMMING, 70);
System.out.println(map.toString());
}
}

Explanation

In the code above, we:

  • Create an Enum for the subjects with the name Subject.

  • Create an EnumMap with the name map.

  • Add three entries to map.

  • Use the toString() method to get the string representation of map.

Free Resources