Java > Java Collections Framework > List, Set, and Map Interfaces > NavigableMap and SortedMap

NavigableMap and SortedMap Example

This code demonstrates the usage of NavigableMap and SortedMap interfaces in Java, focusing on their ability to provide sorted views and navigation capabilities within a map.

Code Demonstration

This code demonstrates how to use NavigableMap and SortedMap features using a TreeMap. We create a TreeMap and populate it with key-value pairs. We then showcase methods like headMap, tailMap, and subMap from the SortedMap interface, which return sorted sub-maps. The NavigableMap interface methods like lowerKey, floorKey, ceilingKey, and higherKey provide ways to navigate the map based on key comparisons. Finally, the code retrieves and prints the first and last entries.

import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

public class NavigableMapExample {

    public static void main(String[] args) {
        // Creating a TreeMap, which implements NavigableMap
        NavigableMap<String, Integer> navigableMap = new TreeMap<>();

        // Adding elements
        navigableMap.put("A", 1);
        navigableMap.put("C", 3);
        navigableMap.put("B", 2);
        navigableMap.put("D", 4);
        navigableMap.put("E", 5);

        System.out.println("NavigableMap: " + navigableMap);

        // SortedMap operations
        SortedMap<String, Integer> headMap = navigableMap.headMap("C"); // Excludes "C"
        System.out.println("SortedMap headMap(\"C\"): " + headMap);

        SortedMap<String, Integer> tailMap = navigableMap.tailMap("C"); // Includes "C"
        System.out.println("SortedMap tailMap(\"C\"): " + tailMap);

        SortedMap<String, Integer> subMap = navigableMap.subMap("B", "D"); // Includes "B", Excludes "D"
        System.out.println("SortedMap subMap(\"B\", \"D\"): " + subMap);

        // NavigableMap specific operations
        String lowerKey = navigableMap.lowerKey("C"); // Key strictly less than "C"
        System.out.println("lowerKey(\"C\"): " + lowerKey);

        String floorKey = navigableMap.floorKey("C"); // Key less than or equal to "C"
        System.out.println("floorKey(\"C\"): " + floorKey);

        String ceilingKey = navigableMap.ceilingKey("C"); // Key greater than or equal to "C"
        System.out.println("ceilingKey(\"C\"): " + ceilingKey);

        String higherKey = navigableMap.higherKey("C"); // Key strictly greater than "C"
        System.out.println("higherKey(\"C\"): " + higherKey);

        // Getting the first and last entries
        System.out.println("First Entry: " + navigableMap.firstEntry());
        System.out.println("Last Entry: " + navigableMap.lastEntry());
    }
}

Concepts Behind the Snippet

The SortedMap interface extends the Map interface and guarantees that the entries are sorted according to the natural ordering of its keys or by a Comparator provided at map creation time. The NavigableMap interface extends SortedMap and provides navigation methods reporting closest matches for given search targets. TreeMap is a concrete implementation of NavigableMap and SortedMap, using a red-black tree structure to ensure efficient sorting and retrieval.

Real-Life Use Case

Consider a scenario where you need to store and retrieve product prices based on their names in a sorted manner. You might also need to find the product with the price just below or above a certain threshold. A NavigableMap is ideal for such cases. For example, an e-commerce application might use this to quickly find the nearest priced items during a sale or price comparison.

Best Practices

  • Use NavigableMap when you need sorted key-value pairs and navigation capabilities.
  • Choose TreeMap as the implementation unless you have very specific performance requirements that necessitate a custom implementation.
  • Be mindful of the natural ordering of keys or provide a custom Comparator to ensure the desired sorting.

Interview Tip

Be prepared to discuss the differences between SortedMap and NavigableMap, and their implementations. Also, be ready to explain when you would choose one over the other. A good understanding of the underlying data structures (like red-black trees for TreeMap) will also impress the interviewer.

When to Use Them

Use SortedMap when you need a map that maintains its entries in sorted order by key. Use NavigableMap when you require additional navigation methods (like finding the floor, ceiling, lower, or higher keys) along with the sorted map functionality.

Memory Footprint

TreeMap, the most common implementation of NavigableMap, has a memory footprint that is generally higher than a HashMap because it needs to maintain the tree structure for sorting. Each entry requires additional memory for node pointers.

Alternatives

If you only need a sorted collection of keys or values, consider using a TreeSet or a sorted List in conjunction with a HashMap. If sorting isn't critical, a HashMap might be more efficient.

Pros

  • Provides sorted key-value pairs.
  • Offers navigation capabilities to find the closest matches for given search targets.
  • Guarantees logarithmic time complexity for most operations (add, remove, get, put).

Cons

  • Higher memory footprint compared to unsorted maps like HashMap.
  • Performance overhead due to maintaining the sorted order.

FAQ

  • What is the difference between SortedMap and NavigableMap?

    SortedMap is an interface that guarantees elements are stored in a sorted manner, either by natural ordering or by a provided Comparator. NavigableMap extends SortedMap and adds methods for navigating the map (e.g., finding the nearest key to a given key).
  • What is the most common implementation of NavigableMap?

    The most common implementation of NavigableMap is TreeMap, which uses a red-black tree to maintain the sorted order.
  • When would I use a NavigableMap over a HashMap?

    You would use a NavigableMap when you need the elements to be sorted and you require navigation capabilities, such as finding the nearest key. If you don't need sorting or navigation, a HashMap is generally more efficient.