Search code examples
javahashmaphashtabletreemap

How to get all the key-values underlying between two given keys in a sorted hashmap?


I have a HashMap with Time as key. I sorted the HashMap. Now I want to get all the key-values between two keys i.e. time values.


Solution

  • Here's some example code. A TreeMap implements the interface NavigableMap, so make sure you use that as your variable type, to harness the full power of a TreeMap:

    NavigableMap<Integer, String> map = new TreeMap<>();
    // code to fill my map with values from 1 to 20, key=int, value=String.valueOf(int)
    IntStream.rangeClosed(1,20).forEach(i->map.put(i, String.valueOf(i)));
    

    NavigableMap has a method .subMap(start, end) and an overload .subMap(start, startInclusive, end, endInclusive) for selecting a partial view of the map, and it sounds like this is what you need.

    NavigableMap<Integer, String> subMap = map.subMap(5, false, 10, false);
    

    This is a live view of the map I created before, but it contains only the mappings between keys 5 and 10, exclusive. Let's check whether that works as expected:

    subMap.forEach(
        (k, v) -> System.out.printf("Key: %d, value: '%s'%n", k, v)
    );
    

    Output:

    Key: 6, value: '6'
    Key: 7, value: '7'
    Key: 8, value: '8'
    Key: 9, value: '9'

    As you can see, the map remains sorted, but is limited to the specified range.