Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the TreeMap.get() method in Java?

Harsh Jain

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.

Answers Code

In this shot, we will learn how to use the TreeMap.get() method in Java.

Introduction

The TreeMap.get() method is present in the TreeMap class inside the java.util package.

The TreeMap.get() method is used to obtain the value associated with the given key on the TreeMap. If no such key is present in the TreeMap, the method returns null.

Syntax

The syntax of the TreeMap.get() method is given below:

V TreeMap.get(K key);

Parameters

The TreeMap.get() method accepts one parameter:

  • Key: The key for which we need to determine the associated value.

Return value

The TreeMap.get() method can return one of values mentioned below:

  • Value: Returns the value associated with that key.
  • NULL: If no such key is present in the TreeMap.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();
t1.put(1, "Let's");
t1.put(5, "see");
t1.put(2, "TreeMap class");
t1.put(27, "methods");
t1.put(9, "in java.");
System.out.println("The value for key = 2 is: " + t1.get(2));
System.out.println("The value for key = 11 is: " + t1.get(11));
}
}
Using the TreeMap.get() method in Java

Explanation

  • In line 1, we import the required package.

  • In line 2, we make a Main class.

  • In line 4, we make a main() function.

  • In line 6, we declare a TreeMap that consists of keys of type Integer and values of type String.

  • From lines 8 to 12, we use the TreeMap.put() method to insert values in the TreeMap.

  • In line 14, we use the TreeMap.get() method to get the value for key=2key = 2.

  • In line 15, we use the TreeMap.get() method to get the value for key=11key = 11. This key is not present, so we get the output value as NULL.

So, this is the way to use the TreeMap.get() method in Java.

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.

Answers Code
Keep Exploring