Tuesday 3 June 2014

HashMap : entrySet() : Get all the Entries in the Map

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

import java.util.*;

class HashMapEntrySet{
  public static void main(String args[]){
    HashMap<Integer, String> myMap1 = new HashMap<> ();
  
  /* Add data to the myMap1 */
  myMap1.put(1, "First");
  myMap1.put(2, "Second");
  myMap1.put(3, "Third");
  myMap1.put(4, "Fourth");
  
  System.out.println("Key\tValue");
  Set<Map.Entry<Integer, String>> mySet = myMap1.entrySet();
  
  for(Map.Entry<Integer, String> entry : mySet){
  System.out.print(entry.getKey() +"\t");
  System.out.println(entry.getValue());
  }
  }
}


Output
Key     Value
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 HashMapEntrySetEx{
  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);
  System.out.println("\nUpdating the Entries using entrySet\n");
  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}

Updating the Entries using entrySet

Elements in the Map are {1=default, 2=default, 3=default, 4=default}




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment