Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the EnumMap.get() 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.

The get method can be used to get the value associated with the specified key in the EnumMap. If the key has no mapping, then null is returned.

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

Syntax

The following is the syntax for the get method of EnumMap:

public V get(Object key)

Parameters

The method expects the key for the value to be returned as an argument.

Return Value

The get method of EnumMap will return:

  • The Value associated with the passed key if there is a mapping present for the passed key.

  • null if there is no mapping present for the passed key.

Code

The code below demonstrates how to use the get method:

import java.util.EnumMap;
class Gett {
enum Days{
MON, TUE, WED, THUR, FRI, SAT, SUN
};
public static void main( String args[] ) {
EnumMap<Days, String> map = new EnumMap<>(Days.class);
map.put(Days.MON, "chest");
System.out.println( "The map is" + map);
System.out.println("map.get(Days.MON) : "+ map.get(Days.MON));
System.out.println("map.get(Days.FRI) : "+ map.get(Days.FRI));
}
}
Using the "get" method to get the value of specific key

Explanation

In the code above:

  • In line 1, we import the EnumMap class.

  • In line 3, we create an enum for days of the week with the name Days.

  • In line 7, we create an EnumMap object with the name map.

  • In line 8, we use the put method to add a mapping Days.MON="chest" to the map object.

  • In line 10, we call the get method for the key Days.MON. This will return the value associated with the key Days.MON. In our case, "chest" is returned.

  • In line 11, we call the get method for the key Days.FRI. This will return null because there is no value associated with the key Days.FRI.

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