TreeMap V get(Object key) method in java

Let’s learn TreeMap V get(Object key) method in java.

TreeMap V get(Object key) method in java

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

Syntax:

public V get(Object key)

Parameters:

key the key whose associated value is to be returned.

Throws:

ClassCastException – if the specified key cannot be compared with the keys currently in the map.

NullPointerException – if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

Also read – TreeMap in java

Now let’s see example on TreeMap V get(Object key) method.

import java.util.TreeMap;
public class TreeMapGetObjectMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(2, "tejas");
      tm.put(1, "om");
      tm.put(3, "tarun");
      tm.put(6, "siddarth");
      tm.put(5, "fanindra");
      System.out.println("Check value of key 5: ");
      System.out.println("Value is: " + tm.get(5));
   }
}


Output:

Check value of key 5:
Value is: fanindra