Java – headMap, tailMap and subMap in NavigableMap

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.

        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

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

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

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

tailMap example.

        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

key: 3, value: 3
key: 4, value: 4

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

subMap example

        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

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

descendingKeySet() and descendingMap()

ceilingKey(), floorKey(), higherKey() and lowerKey()

celingEntry(), floorEntry(), higherEntry(), lowerEntry()

pollFirstEntry() and pollLastEntry()
Advertisements
This entry was posted in Java, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s