Monday 30 July 2012

How to get all keys in Java HashMap?


This Java Example shows how to retrieve all keys contained in HashMap using keySet method of Java HashMap class.


import java.util.HashMap;
import java.util.Set;

public class GetKeysFromHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap

  HashMap phoneBook = new HashMap();

  /**
   * Add key value pair to HashMap using Object put(Object key, Object
   * value) method of Java HashMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * Set keySet() - Returns a set view of the keys contained in this map.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

 }
}


The output is:


Names in the phone book are :
Name: Roy
Name: Joy
Name: John

No comments:

Post a Comment