Java Utility Library

Java TreeMap - get() Method



The java.util.TreeMap.get() method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null.

Syntax

public V get(Object key)

Here, V is the type of value maintained by the container.


Parameters

key Specify the key whose associated value is to be returned.

Return Value

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Exception

  • Throws ClassCastException, if the specified key cannot be compared with the keys currently in the map.
  • Throws NullPointerException, if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

Example:

In the example below, the java.util.TreeMap.get() method returns the value to which the specified key is mapped in the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating the map
    MyMap.put(102, "John");
    MyMap.put(103, "Marry");
    MyMap.put(101, "Kim");
    MyMap.put(104, "Jo");

    //printing mapped value of specified key
    System.out.println("101 is mapped to: " + MyMap.get(101));
    System.out.println("102 is mapped to: " + MyMap.get(102));
    System.out.println("103 is mapped to: " + MyMap.get(103));
    System.out.println("104 is mapped to: " + MyMap.get(104));  
  }
}

The output of the above code will be:

101 is mapped to: Kim
102 is mapped to: John
103 is mapped to: Marry
104 is mapped to: Jo

❮ Java.util - TreeMap