Let’s learn TreeMap navigableKeySet() method in java.
TreeMap navigableKeySet() method in java
navigableKeySet() method of TreeMap class returns a NavigableSet view of the keys contained in this map. The set’s iterator returns the keys in ascending order.
The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined.
The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.
It does not support the add or addAll operations.
Syntax:
public NavigableSet<K> navigableKeySet()
Now let’s see example on TreeMap navigableKeySet() method.
import java.util.NavigableSet; import java.util.TreeMap; public class TreeMapNavigableKeySetMethodExample { public static void main(String[] args) { try { TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); tm.put(11, "apple"); tm.put(12, "banana"); tm.put(13, "grapes"); tm.put(14, "orange"); tm.put(15, "pineapple"); System.out.println("Given TreeMap: " + tm); // get NavigableSet view of keys using navigableKeySet() method NavigableSet<Integer> ns = tm.navigableKeySet(); System.out.println("Value is: " + ns); } catch(NullPointerException ex) { System.out.println("Exception: " + ex); } } }
Output:
Given TreeMap: {11=apple, 12=banana, 13=grapes, 14=orange, 15=pineapple}
Value is: [11, 12, 13, 14, 15]
Let’s see another example on TreeMap navigableKeySet() method.
import java.util.NavigableSet; import java.util.TreeMap; public class TreeMapNavigableKeySetMethodExample { public static void main(String[] args) { try { TreeMap<String, Integer> tm = new TreeMap<String, Integer>(); tm.put("apple", 11); tm.put("banana", 12); tm.put("grapes", 13); tm.put("orange", 14); tm.put("pineapple", 15); System.out.println("Given TreeMap: " + tm); // get NavigableSet view of keys using navigableKeySet() method NavigableSet<String> ns = tm.navigableKeySet(); System.out.println("Value is: " + ns); } catch(NullPointerException ex) { System.out.println("Exception: " + ex); } } }
Output:
Given TreeMap: {apple=11, banana=12, grapes=13, orange=14, pineapple=15}
Value is: [apple, banana, grapes, orange, pineapple]
Also read – major features of java