NavigableMap

In this chapter you will learn:

  1. How to use NavigableMap

Use NavigableMap

Navigable map is a sorted map that can be iterated over in descending order as well as ascending order. Navigable maps are described by the NavigableMap interface, whose generic type is NavigableMap<K,V>, which extends SortedMap.

TreeMap is an example of a navigable map.

import java.util.Iterator;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.TreeMap;
/* ja v a 2  s  .c  om*/
public class Main {
  public static void main(String[] args) {
    NavigableMap<String, Integer> navigableMap = new TreeMap<String, Integer>();
    String[] letters = { "a", "b", "c" };
    int[] ints = { 3, 2, 1 };
    for (int i = 0; i < letters.length; i++){
      navigableMap.put(letters[i], ints[i]);
    }
    System.out.println("Map = " + navigableMap);
    NavigableSet<String> ns = navigableMap.navigableKeySet();
    Iterator iter = ns.iterator();
    while (iter.hasNext()){
      System.out.print(iter.next() + " ");
    }
    System.out.println();
    ns = navigableMap.descendingKeySet();
    iter = ns.iterator();
    while (iter.hasNext()){
      System.out.print(iter.next() + " ");
    }      
    System.out.println();
    System.out.println("First entry = " + navigableMap.firstEntry());
    System.out.println("Last entry = " + navigableMap.lastEntry());
    System.out.println("Entry < a is " + navigableMap.lowerEntry("a"));
    System.out.println("Entry > c is " + navigableMap.higherEntry("c"));
    System.out.println("Poll first entry: " + navigableMap.pollFirstEntry());
    System.out.println("Map = " + navigableMap);
    System.out.println("Poll last entry: " + navigableMap.pollLastEntry());
    System.out.println("Map = " + navigableMap);
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to get keys with greater value
  2. How to get key with value less than a give value
  3. How to get greater key value for a given key
  4. How to get greatest key value for a given key
Home » Java Tutorial » Map
Map interface
Map element adding
Map.Entry class
Map key
Map value
Map key/value search
Map delete/remove
Map comparison
HashMap Class
HashMap search
HashMap clone
TreeMap
TreeMap key
TreeMap head sub map
TreeMap tail sub map
TreeMap sub map
NavigableMap
NavigableMap key
NavigableMap key-value pair
LinkedHashMap Class
IdentityHashMap
SortedMap