Saturday 7 June 2014

TreeMap : keySet() : Get All keys in TreeMap

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

import java.util.*;

class TreeMapKeySet{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Set<Integer> mySet;
  
  myMap = new TreeMap<> ();
  
  /* Add Data to myMap */
  myMap.put(100, "Hi");
  myMap.put(25, "How");
  myMap.put(31, "Are");
  
  mySet = myMap.keySet();

  System.out.println("Keys in myMap are");
  System.out.println(mySet);  
 }
}

Output
Keys in myMap are
[25, 31, 100]

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 TreeMapKeySet1{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Set<Integer> mySet;
  
  myMap = new TreeMap<> ();
  
  /* Add Data to myMap */
  myMap.put(100, "Hi");
  myMap.put(25, "How");
  myMap.put(31, "Are");
  
  mySet = myMap.keySet();

  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  System.out.println("Keys in myMap are");
  System.out.println(mySet); 

  System.out.println("\nRemoving Key 100 from mySet");
  mySet.remove(100);
  
  System.out.println("\nElements in myMap are");
  System.out.println(myMap);
  System.out.println("Keys in myMap are");
  System.out.println(mySet); 
  
  System.out.println("\nAdding a Key 99 to myMap");
  myMap.put(99, "wxyz");
  
  System.out.println("\nElements in myMap are");
  System.out.println(myMap);
  System.out.println("Keys in myMap are");
  System.out.println(mySet); 
 }
}

Output
Elements in myMap are
{25=How, 31=Are, 100=Hi}
Keys in myMap are
[25, 31, 100]

Removing Key 100 from mySet

Elements in myMap are
{25=How, 31=Are}
Keys in myMap are
[25, 31]

Adding a Key 99 to myMap

Elements in myMap are
{25=How, 31=Are, 99=wxyz}
Keys in myMap are
[25, 31, 99]



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment