HashMap overview
Its basically designed to store key value pairs
HashMap class implements the Map interface and it is built using hashtable
Main features of HashMap
It stores data in the form of key-value pair
Keys in the HashMap must be unique
It allows one Null key and multiple Null values
It does not maintain the order of insertion
Value can be retrieved by passing key
If passed key is not exist in the HashMap then value returned will be Null
HashMap can be created using constructor as below
- HashMap<Integer,String> map = new HashMap<Integer,String>();
HashMap<Integer,String> map = new HashMap<Integer,String>();
Most Important Methods in Hashmap
put(Object key, Object value)
This method stores the specified value and associates it with the specified key in this map.
get(Object key)
This method will return the value associated with a specified key in hashmap.
We can add key value pair as below
- map.put(1,”one”);
map.put(1,”one”);
We can retrieve value for the specific key as
- map.get(1);
map.get(1);
Example
- import java.util.*;
- public class HashMapExample {
- public static void main(String args[]) {
- HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
- hashMap.put(1, "One");
- hashMap.put(2, "Two");
- hashMap.put(3, "Three");
- hashMap.put(4, "Four");
- hashMap.put(5, "Five");
- System.out.println(hashMap);
- System.out.println("Value for the key 1 is "+hashMap.get(1));
- System.out.println("Value for the key 10 is "+hashMap.get(10));
- }
- }
import java.util.*; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); hashMap.put(1, "One"); hashMap.put(2, "Two"); hashMap.put(3, "Three"); hashMap.put(4, "Four"); hashMap.put(5, "Five"); System.out.println(hashMap); System.out.println("Value for the key 1 is "+hashMap.get(1)); System.out.println("Value for the key 10 is "+hashMap.get(10)); } }
Note : We can see that corresponding value for existing key is retrieved and value for non-existing key is returned as Null
When to use HashMap?
Whenever we want to store data in key-value pair format
Whenever we don’t worry about order of insertion
When not to use HashMap ?
Whenever we have collection of elements without any link in that data like key value pair
Whenever we need to maintain the order of insertion