Java, with a LinkedHashMap and using removeEldestEntry

  • 11
    public class Logger {
        public Map<String, Integer> map;
        int lastSecond = 0;
        /** Initialize your data structure here. */
        public Logger() {
            map = new java.util.LinkedHashMap<String, Integer>(100, 0.6f, true) {
                protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
                    return lastSecond - eldest.getValue() > 10;
        /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
            If this method returns false, the message will not be printed.
            The timestamp is in seconds granularity. */
        public boolean shouldPrintMessage(int timestamp, String message) {
            lastSecond = timestamp;
            if(!map.containsKey(message)||timestamp - map.get(message) >= 10){
                return true;
            return false;

  • 1

    Thumbs up for the smart usage of LinkedHashMap. Your solution deserves more votes!

  • 1

    @eaglesky Yeah I think this is the natural next question in an interview to build off the first: now add an ejection policy to prevent the hashmap from getting too large.

  • 0
    This post is deleted!

  • 0

    Great and simple enhance to deal with stale messages. How about concurrent issue?

  • 0

    @agnhugo said in Java, with a LinkedHashMap and using removeEldestEntry:

    return lastSecond - eldest.getValue() > 10;

    I think it should be >= to keep the size of map is always equal to 10?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.