HashMap is an implementation of the Map interface that provides a Data Structure to store data in Key-Value pairs.
1. Declaring HashMap
Map<KeyType, ValueType> myMap = new HashMap<KeyType, ValueType>();
KeyType and ValueType must be valid types in Java, such as - String, Integer, Float or any custom class like Employee, Student etc..
For Example :
Map<String,Integer> myMap = new HashMap<String,Integer>();
2. Putting values in HashMap.
To put a value in the HashMap, we have to call
put method on the HashMap object by passing the Key and the Value as parameters.
myMap.put("key1", 1); myMap.put("key2", 2);
If you call the put method with the Key that already exists in the Map, the method will override its value and return the old value.
3. Getting values from HashMap.
For getting the value from a HashMap you have to call the
get method, by passing the Key as a parameter.
myMap.get("key1"); //return 1 (class Integer)
If you pass a key that does not exists in the HashMap, this method will return
4. Check whether the Key is in the Map or not.
5. Check whether the Value is in the Map or not.
The above methods will return a
boolean value true or false if key, value exists in the Map or not.