Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}
Converting map to string

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring