Curriculum
In Java, a NavigableMap
is an interface that extends the SortedMap
interface and provides additional methods for navigation purposes. It allows us to perform operations like finding the closest key, getting the next or previous key, and finding a range of keys based on a range of values or a set of conditions. Here is an overview of NavigableMap
along with examples.
import java.util.NavigableMap; import java.util.TreeMap; public class NavigableMapExample { public static void main(String[] args) { // Creating a TreeMap (which implements NavigableMap) with natural ordering NavigableMap<Integer, String> map1 = new TreeMap<>(); map1.put(3, "Three"); map1.put(1, "One"); map1.put(5, "Five"); System.out.println(map1); // Output: {1=One, 3=Three, 5=Five} // Finding the first key that is greater than or equal to a given key System.out.println(map1.ceilingKey(2)); // Output: 3 // Finding the last key that is less than or equal to a given key System.out.println(map1.floorKey(4)); // Output: 3 // Getting a submap of the map between two keys (inclusive of the start key and exclusive of the end key) NavigableMap<Integer, String> subMap = map1.subMap(2, false, 4, true); System.out.println(subMap); // Output: {3=Three} // Getting the next and previous keys of a given key System.out.println(map1.higherKey(1)); // Output: 3 System.out.println(map1.lowerKey(5)); // Output: 3 } }
The following are some commonly used methods of NavigableMap
interface:
Map.Entry<K,V> ceilingEntry(K key)
: Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.K ceilingKey(K key)
: Returns the least key greater than or equal to the given key, or null if there is no such key.Map.Entry<K,V> floorEntry(K key)
: Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.K floorKey(K key)
: Returns the greatest key less than or equal to the given key, or null if there is no such key.NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
: Returns a view of the portion of this map whose keys range from fromKey
to toKey
.K higherKey(K key)
: Returns the least key strictly greater than the given key, or null if there is no such key.K lowerKey(K key)
: Returns the greatest key strictly less than the given key, or null if there is no such key.NavigableMap<Integer, String> map = new TreeMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); map.put(4, "Four"); map.put(5, "Five"); // Using ceilingEntry and floorEntry methods System.out.println(map.ceilingEntry(2)); // Output: 2=Two System.out
Â