In this guide, you will learn about the TreeMap firstKey() method in Java programming and how to use it with an example.
1. TreeMap firstKey() Method Overview
Definition:
The firstKey() method of the TreeMap class in Java is used to retrieve the first (lowest) key currently in this sorted map. TreeMap is sorted according to the natural ordering of its keys or by a comparator provided at map creation time.
Syntax:
public K firstKey()
Parameters:
- The method does not take any parameters.
Key Points:
- The firstKey() method returns the first (lowest) key currently in the TreeMap.
- If the map is empty, calling firstKey() will throw a NoSuchElementException.
- The method provides a means to access the keys in ascending order.
2. TreeMap firstKey() Method Example
import java.util.TreeMap;
public class TreeMapFirstKeyExample {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Putting some key-value pairs in the TreeMap
treeMap.put(3, "Three");
treeMap.put(1, "One");
treeMap.put(2, "Two");
// Printing the original TreeMap
System.out.println("Original TreeMap: " + treeMap);
// Using firstKey() to retrieve the first key in the TreeMap
Integer firstKey = treeMap.firstKey();
System.out.println("First Key: " + firstKey);
// Removing the first key and retrieving the new first key
treeMap.remove(firstKey);
Integer newFirstKey = treeMap.firstKey();
System.out.println("New First Key after removal: " + newFirstKey);
// Printing the updated TreeMap
System.out.println("Updated TreeMap: " + treeMap);
}
}
Output:
Original TreeMap: {1=One, 2=Two, 3=Three} First Key: 1 New First Key after removal: 2 Updated TreeMap: {2=Two, 3=Three}
Explanation:
In this example, a TreeMap is created and populated with some key-value pairs.
The firstKey() method is then used to retrieve the first key in the map. The retrieved key is then removed from the map, and firstKey() is called again to find the new first key in the updated TreeMap.
The output shows the original TreeMap, the retrieved first keys, and the TreeMap after the removal of the first key.
Comments
Post a Comment
Leave Comment