Java’s TreeMap.firstEntry() Method Explained
Introduction
The java.util.TreeMap class is part of Java’s collections framework, and it is a map implementation that keeps keys in a sorted order. In this article, we be looking into the firstEntry() method of the TreeMap class, which returns the map entry with the smallest key. We'll explore its functionality, compare it with similar methods such as pollFirstEntry(), and show some practical use cases like its application in priority queues.
TreeMap and firstEntry() Basics
The TreeMap class in Java implements the NavigableMap interface, which extends the SortedMap interface. One of the key features of TreeMap is that it keeps its entries sorted based on their keys, either by the natural ordering of the keys or by a custom comparator provided at the time of the map's creation.
What is firstEntry()?
The firstEntry() method in TreeMap returns the key-value pair (entry) with the lowest key in the map. If the map is empty, it returns null.
Syntax:
public Map.Entry<K,V> firstEntry()The firstEntry() method doesn't modify the map, it simply retrieves the first (smallest) key-value pair without removing it. This method is useful when working with sorted data structures where accessing the entry with the smallest key is a frequent operation.
Understanding firstEntry() and pollFirstEntry()
In this section, we will go deeper into two methods from the TreeMap class: firstEntry() and pollFirstEntry(). Both methods deal with retrieving the entry that has the smallest key, but they serve different purposes. While firstEntry() only fetches the entry, leaving the map unchanged, pollFirstEntry() also removes the entry from the map.
How firstEntry() Works
The firstEntry() method is a non-destructive way of fetching the entry with the smallest key from a TreeMap. This method is helpful when you need to peek at the first element but want to maintain the current structure of the map.
Here’s a breakdown of how firstEntry() behaves:
- Retrieves the smallest key-value pair: Since
TreeMapis a sorted map, the smallest key will always be the first entry in its internal ordering. - Returns the entry, not just the key or value: The method provides access to both the key and the value, unlike
firstKey(), which returns only the key. - Does not modify the map: The main feature of
firstEntry()is that it only retrieves the entry without deleting or changing anything in the map. This is useful when you need to reference the smallest entry multiple times without modifying the underlying data structure.
Let’s look at a practical example where we use firstEntry():
import java.util.TreeMap;
import java.util.Map;
public class TreeMapFirstEntryExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(20, "Project Alpha");
map.put(5, "Project Beta");
map.put(15, "Project Gamma");
// Retrieve the first entry (smallest key)
Map.Entry<Integer, String> firstEntry = map.firstEntry();
System.out.println("First Entry: " + firstEntry.getKey() + " - " + firstEntry.getValue());
}
}Output:
First Entry: 5 - Project BetaIn this example, firstEntry() returns the smallest key-value pair in the map, which has the key 5.
How pollFirstEntry() Works
On the other hand, pollFirstEntry() not only fetches the first entry but also removes it from the map. This method is often used when you need to work through a sorted data structure and discard entries as you process them. It’s a destructive operation, meaning once you poll an entry, it’s no longer available in the map.
Here’s how pollFirstEntry() behaves:
- Fetches the smallest entry: Like
firstEntry(), it retrieves the smallest key-value pair. - Removes the entry from the map: Once the entry is returned, it is removed from the map, reducing its size.
- Returns
nullif the map is empty: If the map has no elements,pollFirstEntry()will returnnull, preventing any errors from occurring.
Example:
import java.util.TreeMap;
import java.util.Map;
public class TreeMapPollFirstEntryExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(40, "Client A");
map.put(10, "Client B");
map.put(30, "Client C");
// Poll the first entry (smallest key) and remove it
Map.Entry<Integer, String> polledEntry = map.pollFirstEntry();
System.out.println("Polled Entry: " + polledEntry.getKey() + " - " + polledEntry.getValue());
// Check the remaining map after polling
System.out.println("Remaining entries: " + map);
}
}Output:
Polled Entry: 10 - Client B
Remaining entries: {30=Client C, 40=Client A}In this example, pollFirstEntry() removes the entry with the smallest key, and the map now only contains the entries with keys 30 and 40.
Comparing firstEntry() and pollFirstEntry()
The firstEntry() method retrieves the smallest key-value pair in the map without removing it, making it ideal for situations where you need to access the entry but keep the map intact. On the other hand, pollFirstEntry() not only retrieves the smallest entry but also removes it from the map, which is useful when processing entries sequentially and you no longer need the smallest entry. If you need to reference the smallest entry multiple times or keep the map's contents intact for future operations, firstEntry() is the appropriate choice. However, if your goal is to process and remove entries (such as in a task queue), pollFirstEntry() is the better option, as it prevents the map from growing indefinitely by discarding processed entries.
When to Use firstEntry() vs pollFirstEntry()
Use firstEntry() when:
- You want to peek at the smallest entry without altering the map.
- You need to reference the first entry multiple times during processing.
- The map’s contents need to stay intact for future operations.
Use pollFirstEntry() when:
- You are processing entries sequentially and no longer need the smallest entry.
- You are implementing a task queue or a priority queue where tasks are processed and removed.
- You want to prevent the map from growing indefinitely by removing processed entries.
Scenario Example: Task Queue Management
Let’s consider a scenario where we manage a task queue where each task has a priority, and we need to fetch and process the highest-priority task.
Get Alexander Obregon’s stories in your inbox
Join Medium for free to get updates from this writer.
Using firstEntry():
import java.util.TreeMap;
import java.util.Map;
public class TaskQueue {
public static void main(String[] args) {
TreeMap<Integer, String> taskQueue = new TreeMap<>();
// Adding tasks with priority levels
taskQueue.put(2, "Submit Report");
taskQueue.put(1, "Fix Critical Bug");
taskQueue.put(3, "Client Meeting");
// Peek at the first task (highest priority) without removing
Map.Entry<Integer, String> firstTask = taskQueue.firstEntry();
System.out.println("First task to handle: " + firstTask.getValue() + " (Priority: " + firstTask.getKey() + ")");
// Map remains unchanged
System.out.println("Remaining tasks: " + taskQueue);
}
}Output:
First task to handle: Fix Critical Bug (Priority: 1)
Remaining tasks: {1=Fix Critical Bug, 2=Submit Report, 3=Client Meeting}Here, the task queue remains unchanged after retrieving the first task with firstEntry().
Using pollFirstEntry():
import java.util.TreeMap;
import java.util.Map;
public class TaskQueuePoll {
public static void main(String[] args) {
TreeMap<Integer, String> taskQueue = new TreeMap<>();
// Adding tasks with priority levels
taskQueue.put(2, "Submit Report");
taskQueue.put(1, "Fix Critical Bug");
taskQueue.put(3, "Client Meeting");
// Fetch and remove the first task (highest priority)
Map.Entry<Integer, String> polledTask = taskQueue.pollFirstEntry();
System.out.println("Task to handle: " + polledTask.getValue() + " (Priority: " + polledTask.getKey() + ")");
// Task queue has been modified
System.out.println("Remaining tasks: " + taskQueue);
}
}Output:
Task to handle: Fix Critical Bug (Priority: 1)
Remaining tasks: {2=Submit Report, 3=Client Meeting}In this example, the first task is not only retrieved but also removed from the queue with pollFirstEntry().
Practical Use Cases of firstEntry()
The firstEntry() method in Java's TreeMap class is highly useful in various scenarios, especially when dealing with sorted data. Its ability to retrieve the entry with the smallest key without modifying the map makes it an ideal choice for applications that require non-destructive access to data. Let’s explore some practical use cases where firstEntry() can be leveraged.
Stock Market Tracking
In stock trading systems, it is often necessary to monitor and manage various stock prices. By using TreeMap to store stock symbols and their current prices, you can use firstEntry() to always get the stock with the lowest price, which might be useful for investors looking to buy at the lowest available price.
Example:
import java.util.TreeMap;
import java.util.Map;
public class StockMarketTracker {
public static void main(String[] args) {
TreeMap<Double, String> stockPrices = new TreeMap<>();
stockPrices.put(100.50, "Stock A");
stockPrices.put(95.75, "Stock B");
stockPrices.put(105.30, "Stock C");
// Get the stock with the lowest price
Map.Entry<Double, String> lowestStock = stockPrices.firstEntry();
System.out.println("Lowest Stock: " + lowestStock.getValue() + " at $" + lowestStock.getKey());
}
}Output:
Lowest Stock: Stock B at $95.75In this example, firstEntry() retrieves the stock with the lowest price, allowing you to monitor which stock is currently the most affordable.
Event Scheduling
Event organizers often deal with scheduling multiple events that occur at different times. Using TreeMap, where the keys represent timestamps, the firstEntry() method can be used to retrieve the event scheduled to occur first. This makes sure that you can easily track and manage upcoming events without disturbing the rest of the schedule.
Example:
import java.util.TreeMap;
import java.util.Map;
public class EventScheduler {
public static void main(String[] args) {
TreeMap<Long, String> events = new TreeMap<>();
// Timestamps represent the event start times in milliseconds
events.put(1660000000000L, "Conference");
events.put(1650000000000L, "Workshop");
events.put(1670000000000L, "Webinar");
// Get the event scheduled to occur first
Map.Entry<Long, String> firstEvent = events.firstEntry();
System.out.println("Next event: " + firstEvent.getValue() + " at timestamp " + firstEvent.getKey());
}
}Output:
Next event: Workshop at timestamp 1650000000000In this scenario, firstEntry() helps identify the event that will happen first, allowing the organizer to stay on top of the schedule without altering the map.
Time-Based Cache Expiration
Caches are widely used in software to store temporary data and improve performance. Sometimes, it is necessary to store cache entries with expiration times. Using a TreeMap where the keys represent expiration timestamps, you can call firstEntry() to access the entry that will expire first, allowing you to handle the expiration efficiently.
Example:
import java.util.TreeMap;
import java.util.Map;
public class CacheExpirationManager {
public static void main(String[] args) {
TreeMap<Long, String> cache = new TreeMap<>();
// Adding items with expiration times in milliseconds
cache.put(1665000000000L, "Cache Item 1");
cache.put(1655000000000L, "Cache Item 2");
cache.put(1675000000000L, "Cache Item 3");
// Retrieve the item that will expire first
Map.Entry<Long, String> expiringItem = cache.firstEntry();
System.out.println("First expiring cache item: " + expiringItem.getValue() + " (Expires at: " + expiringItem.getKey() + ")");
}
}Output:
First expiring cache item: Cache Item 2 (Expires at: 1655000000000)In this example, firstEntry() allows the cache manager to identify which item is due to expire first and take appropriate action before it becomes stale.
High Score Management in Games
In multiplayer games, maintaining and displaying a leaderboard with the highest or lowest scores is a common feature. Using TreeMap, where scores are used as the keys, firstEntry() can be utilized to quickly access the player with the lowest score, enabling easier management of game logic such as eliminations or score boosts for low performers.
Example:
import java.util.TreeMap;
import java.util.Map;
public class GameLeaderboard {
public static void main(String[] args) {
TreeMap<Integer, String> leaderboard = new TreeMap<>();
leaderboard.put(1500, "PlayerA");
leaderboard.put(1200, "PlayerB");
leaderboard.put(1800, "PlayerC");
// Retrieve the player with the lowest score
Map.Entry<Integer, String> lowestScore = leaderboard.firstEntry();
System.out.println("Lowest Scorer: " + lowestScore.getValue() + " with score " + lowestScore.getKey());
}
}Output:
Lowest Scorer: PlayerB with score 1200Here, firstEntry() helps retrieve the player with the lowest score, which can be useful when making decisions like awarding boosts or eliminating players based on their performance.
Conclusion
The TreeMap.firstEntry() method is a powerful tool for retrieving the entry with the smallest key in a sorted map without altering its structure. Whether you're managing stock prices, scheduling events, handling cache expiration, or managing a game leaderboard, firstEntry() provides a non-destructive way to access important data efficiently. By understanding when and how to use it, you can streamline operations that rely on sorted data structures while maintaining performance and flexibility in your applications.
Thank you for reading! If you find this article helpful, please consider highlighting, clapping, responding or connecting with me on Twitter/X as it’s very appreciated and helps keeps content like this free!







