Home » Java programming language

Java TreeMap firstEntry() Method with Example

TreeMap Class firstEntry() method: Here, we are going to learn about the firstEntry() method of TreeMap Class with its syntax and example.
Submitted by Preeti Jain, on February 19, 2020

TreeMap Class firstEntry() method

  • firstEntry() method is available in java.util package.
  • firstEntry() method is used to retrieve the key-value pairs linked with the lowest value key element that exists in this TreeMap.
  • firstEntry() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • firstEntry() method does not throw an exception at the time of returning entry.

Syntax:

    public Map.Entry firstEntry();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is Map.Entry, it retrieves key-value entry with the lowest key element exists otherwise it returns null when this TreeMap is "blank".

Example:

// Java program to demonstrate the example 
// of Map.Entry firstEntry() method of TreeMap 

import java.util.*;

public class FirstEntryOfTreeMap {
    public static void main(String[] args) {
        // Instantiates a TreeMap object
        TreeMap < Integer, String > tree_map = new TreeMap < Integer, String > ();

        // By using put() method is to add
        // key-value pairs in a TreeMap
        tree_map.put(10, "C");
        tree_map.put(20, "C++");
        tree_map.put(50, "JAVA");
        tree_map.put(40, "PHP");
        tree_map.put(30, "SFDC");

        // Display TreeMap 
        System.out.println("TreeMap: " + tree_map);

        // By using firstEntry() method is to return
        // the first entry with the least key value
        // element exists in this TreeMap
        System.out.println("tree_map.firstEntry(): " + tree_map.firstEntry());
    }
}

Output

TreeMap: {10=C, 20=C++, 30=SFDC, 40=PHP, 50=JAVA}
tree_map.firstEntry(): 10=C


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.