Collections: pollFirstEntry and pollLastEntry drain a TreeMap like a queue

pollFirstEntry removes and returns the lowest entry by key order, letting a TreeMap be consumed like a priority queue without a separate iterator.

Code
NavigableMap<String, Integer> scores = new TreeMap<>();
scores.put("Amy", 90);
scores.put("Ben", 75);
scores.put("Cid", 88);
while (!scores.isEmpty()) {
    Map.Entry<String, Integer> lowest = scores.pollFirstEntry();
    System.out.println("Removed lowest key: " + lowest);
}
System.out.println("Remaining: " + scores);
Output
Removed lowest key: Amy=90
Removed lowest key: Ben=75
Removed lowest key: Cid=88
Remaining: {}
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms