TreeMap K firstKey() method in java

Let’s learn TreeMap K firstKey() method in java.

TreeMap K firstKey() method in java

firstKey() method of TreeMap class returns the first (lowest) key currently in this map.

Syntax:

public K firstKey()

Throws:

NoSuchElementException – if this map is empty.

Now let’s see example on TreeMap K firstKey() method.

import java.util.TreeMap;
public class TreeMapFirstKeyMethodExample
{
   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("first key of TreeMap: ");
      System.out.println("First key is: " + tm.firstKey());
   }
}

Output:

first key of TreeMap:
First key is: 1


Also read – polymorphism in java