Program to demonstrate "HashMap" class in Java's Collection Framework

The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. It stores value in pairs i.e key and value we can store data using put( ) method and fetch specific data using get( ) method we can print all data using entrySet( ) method. It has following methods:
  1. void clear( ) : Removes all key/value pairs from the invoking map.
  2. boolean containsKey(Object k) : Returns true if the invoking map contains k as a key. Otherwise, returns false.
  3. boolean containsValue(Object v) : Returns true if the map contains v as a value. Otherwise, returns false.
  4. Set entrySet( ) : Returns a Set that contains the entries in the map.
  5. boolean equals(Object obj) : Returns true if obj is a Map and contains the same entries. Otherwise, returns false.
  6. Object get(Object k) : Returns the value associated with the key k.
  7. Object put(Object k, Object v) : Puts an entry in the invoking map, overwriting any previous value associated with the key.
  8. Object remove(Object k) : Removes the entry whose key equals k.
  9. int size( ) : Returns the number of key/value pairs in the map.
  10. Collection values( ) : Returns a collection containing the values in the map.

import java.util.HashMap;
import java.util.Map;

class MapDemo {

 public static void main(String[] args) {
  Map<String,String> q = new HashMap<String,String>();
  for(Map.Entry<String,String> r :q.entrySet())
   System.out.println(r.getKey() + "  " + r.getValue());

  System.out.println("Get Value For Srilanka " + q.get("Srilanka"));
C:\>java MapDemo
Srilanka  Columbo
WestIndies  Jamayca
Australia  Sydney
India  Delhi
Get Value For Srilanka Columbo

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative