NavigableMap
In this chapter you will learn:
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;
//from j a v a 2 s . c o m
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.
Map = {a=3, b=2, c=1}// jav a 2 s.co m
a b c
c b a
First entry = a=3
Last entry = c=1
Entry < a is null
Entry > c is null
Poll first entry: a=3
Map = {b=2, c=1}
Poll last entry: c=1
Map = {b=2}
Next chapter...
What you will learn in the next chapter:
- How to get keys with greater value
- How to get key with value less than a give value
- How to get greater key value for a given key
- How to get greatest key value for a given key
Home » Java Tutorial » Collections