Saturday 7 June 2014

TreeMap : navigableKeySet () : get Navigable set view of keys

public NavigableSet<K> navigableKeySet()
Returns a NavigableSet view of the keys contained in this map.

import java.util.*;

class TreeMapNavigableSet{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  NavigableSet<Integer> navSet;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap */
  myMap.put(2, "w");
  myMap.put(4, "wx");
  myMap.put(6, "wxy");
  myMap.put(8, "wxyz");
  
  navSet = myMap.navigableKeySet();  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  
  System.out.println("Elements in Navigable Set are");
  System.out.println(navSet);   
 }
}


Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Elements in Navigable Set are
[2, 4, 6, 8]

1. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

import java.util.*;

class TreeMapNavigableSet1{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  NavigableSet<Integer> navSet;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap */
  myMap.put(2, "w");
  myMap.put(4, "wx");
  myMap.put(6, "wxy");
  myMap.put(8, "wxyz");
  
  navSet = myMap.navigableKeySet(); 
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  System.out.println("Elements in Navigable Set are");
  System.out.println(navSet); 

  System.out.println("\nRemoving key 4 from navSet");
  navSet.remove(4);
  System.out.println("Add entry 10 to myMap");
  myMap.put(10, "wxyza");
  
  System.out.println("\nElements in myMap are");
  System.out.println(myMap);
  System.out.println("Elements in Navigable Set are");
  System.out.println(navSet); 
  
 }
}

Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Elements in Navigable Set are
[2, 4, 6, 8]

Removing key 4 from navSet
Add entry 10 to myMap

Elements in myMap are
{2=w, 6=wxy, 8=wxyz, 10=wxyza}
Elements in Navigable Set are
[2, 6, 8, 10]



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment