TreeMap firstEntry() Method in Java with Examples
Last Updated :
25 Aug, 2020
TreeMap firstEntry() refers to the method used to retrieve the key-value pairs mapped with the lowest key value element that exists in the TreeMap, if there are no key-value pairs within the Map, simply returns null. The method name ‘firstEntry()’ explains itself that it will return entry having the least key element with its value.
Syntax: public Map.Entry<K,V> firstEntry(),
Here K and V refer key-value respectively.
Parameters: NA - As it doesnot accept any parameter.
Return Value: It returns an entry with the least key (lowest key-value pair) and null if the
TreeMap is empty.
Exception: NA - As it doesnot throw any exception at entry return.
Example 1:
Java
import java.io.*;
import java.util.*;
public class treeMapFirstKey {
public static void main(String[] args)
{
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
treemap.put( 2 , "Java" );
treemap.put( 4 , "CPP" );
treemap.put( 5 , "PHP" );
treemap.put( 1 , "Python" );
treemap.put( 3 , "C" );
System.out.println( "Lowest Entry is: " + treemap.firstEntry());
}
}
|
Output
Lowest Entry is: 1=Python
By the above example, it’s clear that firstEntry() checks compare each key of TreeMap, and returns having the least key-value pair.
Example 2:
Java
import java.io.*;
import java.util.*;
public class percentageFirstKey {
public static void main(String[] args)
{
TreeMap<Double, String> treemapPercentage = new TreeMap<Double, String>();
treemapPercentage.put( 81.40 , "Shashank" );
treemapPercentage.put( 72.80 , "Anand" );
treemapPercentage.put( 65.50 , "Gulshan" );
treemapPercentage.put( 71.10 , "Abhishek" );
treemapPercentage.put( 70.20 , "Ram" );
System.out.println( "Lowest Entry is: " + treemapPercentage.firstEntry());
}
}
|
Output
Lowest Entry is: 65.5=Gulshan
Some points on TreeMap firstEntry():
- TreeMap firstEntry() is available in java.util package.
- It does not throw an exception at return entry time.
- TreeMap firstEntry() method is a non-static method as it is accessible by the class’s object, other than that, will get an error.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...