TreeMap get() method in java

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

TreeMap get() method in java

get() 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 get(Object key) method.

import java.util.TreeMap;
public class TreeMapGetMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(69, "violet");
      tm.put(65, "indigo");
      tm.put(40, "green");
      tm.put(95, "blue");
      tm.put(28, "orange");
      System.out.println("TreeMap Mappings: " + tm);
      // get the value of 69
      System.out.println("Value is: " + tm.get(69));
      // get the value of 95
      System.out.println("Value is: " + tm.get(95));
   }
}


Output:

TreeMap Mappings: {28=orange, 40=green, 65=indigo, 69=violet, 95=blue}
Value is: violet
Value is: blue


Let’s map Integer values to String Keys.

import java.util.TreeMap;
public class TreeMapGetMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
      tm.put("violet", 69);
      tm.put("indigo", 65);
      tm.put("green", 40);
      tm.put("blue", 95);
      tm.put("orange", 28);
      System.out.println("TreeMap Mappings: " + tm);
      // get the value of "violet"
      System.out.println("Value is: " + tm.get("violet"));
      // get the value of "green"
      System.out.println("Value is: " + tm.get("green"));
   }
}


Output:

TreeMap Mappings: {blue=95, green=40, indigo=65, orange=28, violet=69}
Value is: 69
Value is: 40