Showing posts with label keySet(). Show all posts
Showing posts with label keySet(). Show all posts

Using keySet(), entrySet() and values() methods in HashMap

Today we will see about using keySet(), value() and entrySet() methods in HashMap. Basically all these methods will be used to get the list of keys and values from HashMap. Lets see each one separately how its used in Java.
  • keySet() method is used to get only the list of keys in HashMap.
  • value() method is used to get only the list of values in HashMap.
  • entrySet() method is used to get both key and values from the HashMap.

Below is a simple example program which will explain about using all these 3 methods.

 


public class HashMapTest {
 
 public static void main(String[] args) {
 
    Map<String, String> hm = new HashMap<String, String>();
    hm.put("key1", "Bangalore");
    hm.put("key3", "India");
    hm.put("key2", "Mumbai");
    hm.put("key5", "New Delhi");
    hm.put("key4", "Chennai");
    
    new HashMapTest().getOnlyKeyList(hm);
    new HashMapTest().getOnlyValueList(hm);
    new HashMapTest().getBothKeyValue(hm);    
 }
 
 // Fetching only Keys by using keySet() method
 public void getOnlyKeyList(Map<String, String> hm){
  Iterator<String> itr = ((Set<String>) hm.keySet()).iterator();
  System.out.println("USING keyset() :::::::::::: ");
  while(itr.hasNext()){
   String key = itr.next();
   System.out.println("KEY : "+key);
  }
 }
 
 // Fetching only values by using value() method
 public void getOnlyValueList(Map<String, String> hm){
  Iterator<String> itr = hm.values().iterator();
  System.out.println("\n\nUSING value() :::::::::::: ");
  while(itr.hasNext()){
   String value = itr.next();
   System.out.println("VALUE : "+value);
  }
 }
 
 // Fetching both keys and values using entrySet() method
 public void getBothKeyValue(Map<String, String> hm){
  Iterator <Map.Entry<String,String>>entryset = hm.entrySet().iterator();
  System.out.println("\n\nUSING entryset() :::::::::::: ");
  while(entryset.hasNext()){
   Map.Entry <String,String>entry=entryset.next();
   String key = entry.getKey();
   String value = entry.getValue();
   System.out.println("KEY : "+key +" - VALUE : "+value);
  }
 }
}



OUTPUT:



USING keyset() :::::::::::: 
KEY : key1
KEY : key3
KEY : key5
KEY : key2
KEY : key4


USING value() :::::::::::: 
VALUE : Bangalore
VALUE : India
VALUE : New Delhi
VALUE : Mumbai
VALUE : Chennai


USING entryset() :::::::::::: 
KEY : key1 - VALUE : Bangalore
KEY : key3 - VALUE : India
KEY : key5 - VALUE : New Delhi
KEY : key2 - VALUE : Mumbai
KEY : key4 - VALUE : Chennai