Java TreeMap get() Method Example

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

Signature

public V get(Object key)

This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. Throws ClassCastException  if the specified key cannot be compared with the keys currently in the map and NullPointerException  if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys

Example

The following example shows the usage of java.util.TreeMap.get(key) method.

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class GetMethodTreeMapExample
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to populate elements to the TreeMap
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(1,"Element1");
        treeMap1.put(6,"Element6");
        treeMap1.put(5,"Element5");
        
        //get the entrySet of treeMap1
        Set<Map.Entry<Integer,String>> set1 = treeMap1.entrySet();.
        //Print the elements of treeMap1
        System.out.println("**Elements of treeMap1**");
        for (Map.Entry<Integer,String> me : set1) 
        {
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        
        //Get value for the key "6"
        System.out.println("**Value associated with key 6**");
        System.out.println(treeMap1.get(6));
    }
}

Output

**Elements of treeMap1**
1: Element1
2: Element2
3: Element3
5: Element5
6: Element6
**Value associated with key 6**
Element6

Leave a Reply

Your email address will not be published. Required fields are marked *