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:
PROGRAM
- void clear( ) : Removes all key/value pairs from the invoking map.
- boolean containsKey(Object k) : Returns true if the invoking map contains k as a key. Otherwise, returns false.
- boolean containsValue(Object v) : Returns true if the map contains v as a value. Otherwise, returns false.
- Set entrySet( ) : Returns a Set that contains the entries in the map.
- boolean equals(Object obj) : Returns true if obj is a Map and contains the same entries. Otherwise, returns false.
- Object get(Object k) : Returns the value associated with the key k.
- Object put(Object k, Object v) : Puts an entry in the invoking map, overwriting any previous value associated with the key.
- Object remove(Object k) : Removes the entry whose key equals k.
- int size( ) : Returns the number of key/value pairs in the map.
- Collection values( ) : Returns a collection containing the values in the map.
PROGRAM
import java.util.HashMap;
import java.util.Map;
class MapDemo {
public static void main(String[] args) {
Map<String,String> q = new HashMap<String,String>();
q.put("India","Delhi");
q.put("Srilanka","Columbo");
q.put("WestIndies","Jamayca");
q.put("Australia","Sydney");
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"));
}
}
OUTPUT
C:\>javac MapDemo.java C:\>java MapDemo Srilanka Columbo WestIndies Jamayca Australia Sydney India Delhi Get Value For Srilanka Columbo
Comments
Post a Comment