Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface.
When there is no parameter defined while creating HashMap default Initial Capacity(16) and Default load factor(75%) will be used.
Below is the constructor of HashMap
public class HashMap<K;,V> extends AbstractMap<K;,V>
implements Map<K;,V>, Cloneable, Serializable {
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
}
the number of elements a particular collection can hold, yes, collection do not have limit that does not mean java will provide space for all the unlimited members at one shot, the space will be allocated only when it reaches a storage limit.
As I said above, load factor decides when to increase the capacity of the collection, Hash map has load factor of 75% which means
This HashMap can contain up to 16 element and resizing of HashMap will occur when 13th element will be inserted. This is because load factor is 75%(.75) and this threshold will be crossed when you add 13th element(12+1).
You can also provide custom initial capacity and loadFactor. But initial capacity can not be more than maximum capacity (2 power 30) and load factor can not be zero or negative number
Creation of HashMap in Java
// basic syntax
Map<K;, V> basicHashMap = new HashMap();
// map of r key as string and value as integer
Map<String;, Integer> hash = new HashMap();
HashMap<String;, Integer> hashMap = new HashMap();
Sample usage of the HasMap
public class CreateHashMapSample{
public static void main(String[] args) {
// Create HashMap
Map<String;, Integer> hMap = new HashMap();
// Adding keys and values to a HashMap
hMap.put("One", 1);
hMap.put("Two", 2);
hMap.put("Three", 3);
System.out.println(hMap);
}
}
Output of the sample HashMap program
{Three=3, One=1, Two=2}
HashMap has four constructor, these constructors are designed to provide options for users.
Map<K;, V> basicHashMap = new HashMap();
Map<K;, V> basicHashMap = new HashMap(int initial capacity);
Map<K;, V> basicHashMap = new HashMap(int initial capacity, float loadFactor);
Map<K;, V> basicHashMap = new HashMap(Map map)
public class CreateHashMapSample{
public static void main(String[] args) {
// Create HashMap
Map<String;, String> hMap = new HashMap();
}
}
It checks whether the map is empty. If there are no key-value mapping present in the map then this function returns true else false.
// Create HashMap
Map<String;, String> hMap = new HashMap();
System.out.println("Member of the Map : "+hMap);
System.out.println("Is Map empty : " + hMap.isEmpty());
Output of isEmpty()
Member of the Map : {}
Is Map empty : true
Creates a key with respective value in the HashMap. If map contains the same key with different value then the old value is replaced with new Value
Map<String;, String> hMap = new HashMap();
System.out.println("Map before addition : "+hMap);
// add new value
hMap.put("microsoft", "Bing");
System.out.println("Map after addition of key-value: "+hMap);
// update the value with sam key
hMap.put("microsoft", "Operating System");
System.out.println("Map after replacement of key-value: "+hMap);
Output of put()
Map before addition : {}
Map after addition of key-value: {microsoft=Bing}
Map after replacement of key-value: {microsoft=Operating System}
Returns the number of key-value pairs present in the HashMap
Map<String;, String> hMap = new HashMap();
// add new values
hMap.put("microsoft", "Bing");
System.out.println("Map members : "+hMap);
System.out.println("Map size : "+hMap.size());
System.out.println("\n*******Adding win10 (second entry)*******");
hMap.put("win10", "Operating System");
System.out.println("Map members : "+hMap);
System.out.println("Map size : "+hMap.size());
Output of size()
Map members : {microsoft=Bing}
Map size : 1
*******Adding win10 (second entry)*******
Map members : {win10=Operating System, microsoft=Bing}
Map size : 2
clear() method will remove all the entries from the HashMap
Map<String;, String> hMap = new HashMap();
// add new values
hMap.put("microsoft", "Bing");
hMap.put("win10", "Operating System");
System.out.println("Map members before clearing : "+hMap);
hMap.clear();
System.out.println("Map members after clearing : "+hMap);
Output of clear() in HashMap
Map members before clearing : {win10=Operating System, microsoft=Bing}
Map members after clearing : {}
Returns the value mapped to the specified key, or null if there is no mapping for the key.
Map<String;, String> hMap = new HashMap();
// add new values
hMap.put("microsoft", "Bing");
hMap.put("win10", "Operating System");
System.out.println("Get value of 'win10' from Map : " +hMap.get("win10"));
Output of get() method
Get value of 'win10' from Map : Operating System
Removes key from the map along with its value
Map<String;, String> hMap = new HashMap();
// add new values
hMap.put("microsoft", "Bing");
hMap.put("win10", "Operating System");
System.out.println("Map members : " +hMap);
hMap.remove("win10");
System.out.println("Map members after removal of 'win10' : " +hMap);
output after removal of element
Map members : {win10=Operating System, microsoft=Bing}
Map members after removal of 'win10' : {microsoft=Bing}
Copies all of the mappings from the specified map to this map. if we have any keys in both the maps then map the key-value present in the map that we are adding will replace the key-value present in out source map. (highlighted in output)
Map<String;, String> hMap = new HashMap();
System.out.println("Members of hMap: " +hMap);
Map<String;, String> kiddyMap = new HashMap();
kiddyMap.put("larry", "Google");
kiddyMap.put("gates", "microsoft");
System.out.println("Members of Kiddy : "+kiddyMap);
hMap.putAll(kiddyMap);
System.out.println("Members of hMap after adding Kiddy");
System.out.println(hMap);
Output of putAll()
containsKey() method will return true if the given key is present in the map otherwise false, so does containsValue() as well.
Map<String;, String> hMap = new HashMap();
hMap.put("aa", "bbbb");
hMap.put("larry", "Youtube");
System.out.println("Members of hMap: " +hMap);
System.out.println("Contains Key 'abc' : " +hMap.containsKey("abc"));
System.out.println("Contains Value 'Youtube' : " +hMap.containsValue("Youtube"));
output of containsKey & containsValue in HashMap
Members of hMap: {aa=bbbb, larry=Youtube}
Contains Key 'abc' : false
Contains Value 'Youtube' : true
Returns keys present in the map as Set collection.
values() method returns all the values present in the map.
Map<String;, String> hMap = new HashMap();
hMap.put("aa", "bbbb");
hMap.put("larry", "Youtube");
System.out.println("Keys Presesnt in Map : " +hMap.keySet());
System.out.println("Values present in Map : " +hMap.values());
Output of keySet() and values()
Keys Presesnt in Map : [aa, larry]
Values present in Map : [bbbb, Youtube]
Iterate over a collection or data set in Java is a very common task. You can use it to print or manipulate the data.
For each loop is nothing but enhanced for loop, the difference is this loop will not have any loop control variable but the the loops starts with the first item in the collection and incrementally goes till th end.
Once it reaches collection end then loops gets terminated and for every time we will receive the current collection member to perform some operation.
public static void main(String[] args) {
Map<String;, String> map = new HashMap<String;, String>();
map.put("firstKey", "firstValue");
map.put("secondKey", "secondValue");
//enhanced for loop
for (Map.Entry<String;, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
Output of enhanced for loop iteration
firstKey = firstValue
secondKey = secondValue
we can iterate through Map using lambda function in Java 8.
public static void main(String[] args) {
Map<String;, String> map = new HashMap<String;, String>();
map.put("firstKey", "firstValue");
map.put("secondKey", "SecondValue");
// for each with lambda
map.forEach((key,value) -> System.out.println(key + " = " + value));
}
This method uses java.util.Iterator to go through the HashMap, Iterator will be created to the Map object and the pointer point to first element of the object and moves further member once the next() method occurs.
public static void main(String[] args) {
Map<String;, String> map = new HashMap<String;, String>();
map.put("firstKey", "firstValue");
map.put("secndKey", "secondValue");
Iterator> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
We can use the for-each loop to iterate over the keys, we know how do get the keys of a Map , don't you ?
Once we have the set of keys, we can using for-statement to iterate over the keys, and for every key we can retrieve the value in the map using get() method present in the Map
public static void main(String[] args) {
Map<String;, String> map = new HashMap<String;, String>();
map.put("firstKey", "firstValue");
map.put("secndKey", "secondValue");
map.keySet().forEach(key -> {
System.out.println(key + " = " + map.get(key));
});
}
Similar to above method we can also use the enhanced for loop to iterate over the map and values.
public static void main(String[] args) {
Map<String;, String> map = new HashMap<String;, String>();
map.put("firstKey", "firstValue");
map.put("secndKey", "secondValue");
for(Entry entry: map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know.
Knowledge is the only thing that doubles when you spend it.
I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation