Wednesday 4 June 2014

HashMap : keySet : Get All the Keys in the Map

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

import java.util.*;

class HashMapKeySet{
 public static void main(String args[]){
  HashMap<Integer, String> myMap;
  Set<Integer> mySet;
  
  myMap = new HashMap<> ();
  
  /* 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
[100, 25, 31]

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 HashMapKeySet1{
 public static void main(String args[]){
  HashMap<Integer, String> myMap;
  Set<Integer> mySet;
  
  myMap = new HashMap<> ();
  
  /* 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
{100=Hi, 25=How, 31=Are}
Keys in myMap are
[100, 25, 31]

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
{99=wxyz, 25=How, 31=Are}
Keys in myMap are
[99, 25, 31]

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment