LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 20

Draining a TreeMap with pollFirstEntry Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<Integer, String> events = new TreeMap<>(Map.of(1030, "standup", 900, "email", 1400, "review", 1200, "lunch"));
        StringBuilder sb = new StringBuilder();
        Map.Entry<Integer, String> e;
        while ((e = events.pollFirstEntry()) != null) {
            sb.append(e.getKey()).append(':').append(e.getValue()).append(' ');
            if (e.getKey() >= 1200) break;
        }
        System.out.println(sb.toString().trim() + " | left " + events);
    }
}
  • A 900:email 1030:standup 1200:lunch | left {1400=review} Correct
  • B 900:email 1030:standup | left {1200=lunch, 1400=review}
  • C 1400:review | left {}
  • D 900:email 1030:standup 1200:lunch 1400:review | left {}
Correct Answer: Option A

pollFirstEntry removes and returns the smallest key each time – a sorted queue of events.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links