Java range query using TreeMap.subMap()

  • 9

    Given the granularity we can set a lower bound and upper bound of timestamp so we could do a range query using TreeMap. To get the lower bound we append a suffix of "2000:01:01:00:00:00" to the prefix of s and to get the upper bound we append a suffix of "2017:12:31:23:59:59" to the prefix of e.

    public class LogSystem {
        private String min, max;
        private HashMap<String, Integer> map;
        private TreeMap<String, LinkedList<Integer>> logs;
        public LogSystem() {
            min = "2000:01:01:00:00:00";
            max = "2017:12:31:23:59:59";
            map = new HashMap<>();
            map.put("Year", 4);
            map.put("Month", 7);
            map.put("Day", 10);
            map.put("Hour", 13);
            map.put("Minute", 16);
            map.put("Second", 19);
            logs = new TreeMap<>();
        public void put(int id, String timestamp) {
            if(!logs.containsKey(timestamp)) logs.put(timestamp, new LinkedList<>());
        public List<Integer> retrieve(String s, String e, String gra) {
            int index = map.get(gra);
            String start = s.substring(0, index)+min.substring(index), end = e.substring(0, index)+max.substring(index);
            NavigableMap<String, LinkedList<Integer>> sub = logs.subMap(start, true, end, true);
            LinkedList<Integer> ans = new LinkedList<>();
            for (Map.Entry<String, LinkedList<Integer>> entry : sub.entrySet()) {
            return ans;

  • 0

    @dreamchase said in Java range query using TreeMap.subMap():


    I got this error: error: cannot find symbol: class NavigableMap

  • 0

    @hpnhxxwn change it to Map<String, LinkedList<Integer>>, that will work

Log in to reply

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