Monday 14 April 2014

keySet : get All keys from Map

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

import java.util.*;
class MapKeySet{
  public static void main(String args[]){
         Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Add Data to the Map */
  mapEx.put(1, "First");
  mapEx.put(2, "Second");
  mapEx.put(3, "Third");
  mapEx.put(4, "Fourth");
  
  System.out.println("Elements in the map are ");
  System.out.println(mapEx);
  
  /*Get the Keys from the map */
  Set<Integer> keys = mapEx.keySet();
  
  System.out.println("\nKeys in the map are");
  System.out.println(keys);
  }
}


Output
Elements in the map are
{1=First, 2=Second, 3=Third, 4=Fourth}

Keys in the map are
[1, 2, 3, 4]

1. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. By using the set return by keySet method, you can remove the keys from map. But you can't add the keys.

import java.util.*;
class MapKeySetEx{
  public static void main(String args[]){
         Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Add Data to the Map */
  mapEx.put(1, "First");
  mapEx.put(2, "Second");
  mapEx.put(3, "Third");
  mapEx.put(4, "Fourth");
  
  System.out.println("Elements in the map are ");
  System.out.println(mapEx);
  
  /*Get the Keys from the map */
  Set<Integer> keys = mapEx.keySet();
  
  System.out.println("\nKeys in the map are");
  System.out.println(keys);
  
  System.out.println("\nAdding Data to the map");
  
  mapEx.put(5, "Five");
  mapEx.put(6, "Six");
  mapEx.put(7, "Seven");
  mapEx.put(8, "Eight");
  
  System.out.println("\nElements in the map are ");
  System.out.println(mapEx);
  
  System.out.println("\nKeys in the map are");
  System.out.println(keys);
  
  System.out.println("\nRemoving Keys 1,3,5,7 from Map");
  /* Removing Keys from Set */
  keys.remove(1);
  keys.remove(3);
  keys.remove(5);
  keys.remove(7);
  
  System.out.println("\nElements in the map are ");
  System.out.println(mapEx);
  
  System.out.println("\nKeys in the map are");
  System.out.println(keys);
  }
}

Output
Elements in the map are
{1=First, 2=Second, 3=Third, 4=Fourth}

Keys in the map are
[1, 2, 3, 4]

Adding Data to the map

Elements in the map are
{1=First, 2=Second, 3=Third, 4=Fourth, 5=Five, 6=Six, 7=Seven, 8=Eight}

Keys in the map are
[1, 2, 3, 4, 5, 6, 7, 8]

Removing Keys 1,3,5,7 from Map

Elements in the map are
{2=Second, 4=Fourth, 6=Six, 8=Eight}

Keys in the map are
[2, 4, 6, 8]







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment