Java - headMap, tailMap and subMap in NavigableMap

1 minute read

NavigableMap collection on Java provide methods to return the view of Map on sorted order of key. The most common methods are headMap, tailMap and subMap.

headMap example.

1
2
3
4
5
6
7
8
        NavigableMap<String, String> navigableMap = new TreeMap<>();
        navigableMap.put("1", "1");
        navigableMap.put("2", "2");
        navigableMap.put("3", "3");
        navigableMap.put("4", "4");
        SortedMap<String, String> resultViewMap = navigableMap.headMap("3");
        resultViewMap.entrySet().stream().forEach(entry ->
                System.out.println(String.format("key: %s, value: %s", entry.getKey(), entry.getValue())));

output

1
2
key: 1, value: 1
key: 2, value: 2

If inclusive is true on calling headMap("3", true), it will be

1
2
3
key: 1, value: 1
key: 2, value: 2
key: 3, value: 3

tailMap example.

1
2
3
4
5
6
7
8
        NavigableMap<String, String> navigableMap = new TreeMap<>();
        navigableMap.put("1", "1");
        navigableMap.put("2", "2");
        navigableMap.put("3", "3");
        navigableMap.put("4", "4");
        SortedMap<String, String> resultViewMap = navigableMap.tailMap("3");
        resultViewMap.entrySet().stream().forEach(entry ->
                System.out.println(String.format("key: %s, value: %s", entry.getKey(), entry.getValue())));

output

1
2
key: 3, value: 3
key: 4, value: 4

By default, inclusive is true on calling tailMap("3", true).

subMap example

1
2
3
4
5
6
7
8
        NavigableMap<String, String> navigableMap = new TreeMap<>();
        navigableMap.put("1", "1");
        navigableMap.put("2", "2");
        navigableMap.put("3", "3");
        navigableMap.put("4", "4");
        SortedMap<String, String> resultViewMap = navigableMap.subMap("2", "4");
        resultViewMap.entrySet().stream().forEach(entry ->
                System.out.println(String.format("key: %s, value: %s", entry.getKey(), entry.getValue())));

output

1
2
key: 2, value: 2
key: 3, value: 3

By default, inclusive is true for fromKey, and inclusive is false for toKey on calling subMap("2", true, "4", false)

There are more available methods in NavigableMap

1
2
3
4
descendingKeySet() and descendingMap()
ceilingKey(), floorKey(), higherKey() and lowerKey()
celingEntry(), floorEntry(), higherEntry(), lowerEntry()
pollFirstEntry() and pollLastEntry()