Monday 14 April 2014

entrySet : View all mappings in the Map

Set<Map.Entry<K, V>> entrySet()
Return a set view of the mappings contained in this map.

import java.util.*;
class MapEntrySet{
  public static void main(String args[]){
         Map<Integer, String> mapEx = new HashMap<> ();
  
  /* Put the data to 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 " + mapEx);
  
  /* get the Entry Set */
  Set<Map.Entry<Integer, String>>  mySet = mapEx.entrySet();
  
  Iterator iter = mySet.iterator();
  
  System.out.println("\nElements in Entry Set are");
  while(iter.hasNext()){
    System.out.println(iter.next());
  }
  }
}

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

Elements in Entry Set are
1=First
2=Second
3=Third
4=Fourth

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 MapEntrySetEx{
  public static void main(String args[]){
        Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Put the data to 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 " + mapEx);

  for (Map.Entry<Integer, String> entry : mapEx.entrySet()){
   entry.setValue("default");
  }
  
  System.out.println("Elements in the Map are " + mapEx);
  }
}

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









Prevoius                                                 Next                                                 Home

No comments:

Post a Comment