In this article we will dive into Java HashMap and it’s most commonly used methods with examples. Java HashMap is one of the most commonly used implementation of Map interface.
A java HashMap is a map based collection, implementation class of the
java.util.Map
interface and it’s underlying data structure is hash table.
1. HashMap features
- HasMap class implements the
java.util.Map
interface, the under lying data structure is hash table. - Duplicate keys are not allowed but values can be duplicated.
- Insertion order is not preserved and it is based on hash code of the keys.
- Java HashMap class is non synchronized.
- The initial default capacity of Java HashMap class is 16 with a load factor of 0.75. Which means once the map reaches its capacity, the capacity will be increased by 3/4 of initial capacity.
- HashMap methods are not synchronized.
Why and when do we use HashMap in Java? : Basic usage of HashMap in java is to store key value pairs. Each key value pair we call an Entry. Map is a collection of Entry objects. As HashMap internal data structure is hash table, it’s efficient for inserting, deleting and get value based on key when synchronization not important.
2. HashMap class hierarchy
Following image illustrates the hierarchy of Java HashMap class.
3. Create HashMap
Following are the HashMap public constructors to create its instances.
HashMap()
: Constructs an empty HashMap with the default initial capacity 16 and the default load factor 0.75.HashMap(int initial capacity)
: Constructs an empty HashMap with the specified initial capacity and the default load factor 0.75.HashMap(int initial capacity, float loadFactor)
: Constructs an empty HashMap with the specified initial capacity and load factor.HashMap(Map map)
: Constructs a new HashMap with the same mappings as the specified Map, it is useful to convert other map implementations to hashmap.
Below code use to create an empty HashMap with the default initial capacity 16 and the default load factor 0.75.
//An empty HashMap Map<Integer, String> hashMap = new HashMap<Integer, String>();
4. HashMap methods and examples
Let’s have a look into most commonly used HashMap methods that how we process map with simple examples.
4.1. Add key and value pairs to HashMap
Following are the methods to add key-values to the HashMap.
put(k, v)
– To associate the specified value with the specified key in this map.putAll(Map<? extends K,? extends V> m)
– Copies all of the mappings from the specified map to this map.putIfAbsent(K key, V value)
– (Since Java 8) – If the specified key is not already associated with a value (or is mapped tonull
) associates it with the given value and returnsnull
, else returns the current value.
Following example shows you how to add or insert elements to HashMap.
//An empty HashMap Map<Integer, String> hashMap1 = new HashMap<Integer, String>(); //put() hashMap1.put(7, "Peter"); hashMap1.put(5, "Philip"); hashMap1.put(2, "Martin"); System.out.println(hashMap1); //{2=Martin, 5=Philip, 7=Peter} -(order may not same) //An empty HashMap Map<Integer, String> hashMap2 = new HashMap<Integer, String>(); hashMap2.put(1, "Christina"); //putAll() hashMap2.putAll(hashMap1); System.out.println(hashMap2); //{1=Christina, 2=Martin, 5=Philip, 7=Peter} hashMap2.put(8, null); System.out.println(hashMap2.putIfAbsent(8, "Jhohn"));//null System.out.println(hashMap2); //{1=Christina, 2=Martin, 5=Philip, 7=Peter, 8=Jhohn}
Output :
{2=Martin, 5=Philip, 7=Peter} {1=Christina, 2=Martin, 5=Philip, 7=Peter} null {1=Christina, 2=Martin, 5=Philip, 7=Peter, 8=Jhohn}
4.2. Verify HashMap contains value
containsKey(Object key)
– Returns true if this map contains a mapping for the specified key.containsValue(Object value)
– Returns true if this map maps one or more keys to the specified value.
Following example shows you how to verify if a key or value contains HashMap.
public class JavaHashMapContainsDemo { public static void main(String[] args) { Map<Integer, String> hashMap1 = new HashMap<Integer, String>(); // put() hashMap1.put(7, "Peter"); hashMap1.put(5, "Philip"); hashMap1.put(2, "Martin"); // containsKey() System.out.println(hashMap1.containsKey(5));// true // containsValue() System.out.println(hashMap1.containsValue("John"));// false System.out.println(hashMap1.containsValue("Peter"));// true } }
Output :
true false true
4.3. Get or retrieve values from HashMap
get(Object key)
– Returns the value to which the specified key is mapped, ornull
if this map contains no mapping for the key.getOrDefault(Object key, V defaultValue)
– (Since Java 8) – Returns the value to which the specified key is mapped, ordefaultValue
if this map contains no mapping for the key.
Following example shows you how to get a value from HashMap by it’s key and how to get a default value if specified key not exist in the HashMap .
public class HashMapGetDemo { public static void main(String[] args) { Map<Integer, String> hashMap1 = new HashMap<Integer, String>(); // put() hashMap1.put(7, "Peter"); hashMap1.put(5, "Philip"); hashMap1.put(2, "Martin"); // get() System.out.println(hashMap1.get(2));// Martin // getOrDefault() System.out.println(hashMap1.getOrDefault(5, "John"));// Philip System.out.println(hashMap1.getOrDefault(9, "John"));// John } }
Output :
Martin Philip John
4.4. Verify is HashMap empty and size
isEmpty()
– Returns true if this map contains no key-value mappings.size()
– Returns the number of key-value mappings in this map.
Following example shows you how to verify a HashMap is empty or not and how to get the size of a HashMap.
public class HashMapSizeAndIsEmptyDemo { public static void main(String[] args) { Map<Integer, String> hashMap1 = new HashMap<Integer, String>(); // put() hashMap1.put(7, "Peter"); hashMap1.put(5, "Philip"); hashMap1.put(2, "Martin"); // size() System.out.println(hashMap1.size());// 3 // isEmpty() System.out.println(hashMap1.isEmpty());// false //clear() hashMap1.clear(); System.out.println(hashMap1.isEmpty());// true } }
Output :
3 false true
4.5. Replace, remove or clear HashMap
remove(Object key)
– Removes the mapping for the specified key from this map if present.remove(Object key, Object value)
– Removes the entry for the specified key only if it is currently mapped to the specified value.replace(K key, V value)
– (Since Java 8) – Replaces the entry for the specified key only if it is currently mapped to some value.replace(K key, V oldValue, V newValue)
– (Since Java 8) – Replaces the entry for the specified key only if currently mapped to the specified value.clear()
– Removes all of the mappings from this map.
Following example shows you how to remove a value from HashMap by its key, how to replace a value and clear all HashMap elements.
public class HashMapRemoveReplaceClearDemo { public static void main(String[] args) { Map<Integer, String> hashMap1 = new HashMap<Integer, String>(); // put() hashMap1.put(7, "Peter"); hashMap1.put(5, "Philip"); hashMap1.put(2, "Martin"); // replace() hashMap1.replace(2, "Anand"); System.out.println(hashMap1); // {2=Anand, 5=Philip, 7=Peter} // replace(key, old, new) hashMap1.replace(2, "Anand", "Martin"); System.out.println(hashMap1); // {2=Martin, 5=Philip, 7=Peter} // remove() hashMap1.remove(2); System.out.println(hashMap1); // {5=Philip, 7=Peter} // remove(key, exist) hashMap1.remove(7, "Peter"); hashMap1.remove(5, "Peter"); System.out.println(hashMap1);// {5=Philip} // cear() hashMap1.clear(); System.out.println(hashMap1);// {} } }
Output :
{2=Anand, 5=Philip, 7=Peter} {2=Martin, 5=Philip, 7=Peter} {5=Philip, 7=Peter} {5=Philip} {}
4.6. Iterate or loop HashMap
Following methods in HashMap are helpful to iterate or process each key or value or Entry in HashMap.
entrySet()
Returns aSet
of Enrtry ( Child interface of Map and represents key and value) objects contained in this map.keySet()
– Returns aSet
of the keys contained in this map.values()
– Returns aCollection
of the values contained in this map.forEach(BiConsumer action)
– (Since Java 8) – Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. This method useful to iterate or process each element in the HashMap.
The following example shows you how to iterate HashMap in java. You can see detailed examples in how to iterate map article.
public class HashMapIterateDemo { public static void main(String[] args) { Map<Integer, String> hashMap = new HashMap<Integer, String>(); // put() hashMap.put(7, "Peter"); hashMap.put(5, "Philip"); hashMap.put(2, "Martin"); // keySet() for(Integer k : hashMap.keySet()) System.out.println("key : "+k +"- Value : "+ hashMap.get(k)); System.out.println("------------------------------"); // values() for(String v : hashMap.values()) System.out.println("Value : "+v); System.out.println("------------------------------"); // entrySet() for(Map.Entry e : hashMap.entrySet()) System.out.println("key : "+e.getKey() +"- Value : "+ e.getValue()); System.out.println("------------------------------"); // forEach() - java 8 hashMap.forEach((k,v) -> System.out.println("key : "+k +"- Value : "+ v)); } }
Output :
key : 2- Value : Martin key : 5- Value : Philip key : 7- Value : Peter ------------------------------ Value : Martin Value : Philip Value : Peter ------------------------------ key : 2- Value : Martin key : 5- Value : Philip key : 7- Value : Peter ------------------------------ key : 2- Value : Martin key : 5- Value : Philip key : 7- Value : Peter
4.7. Compute mapping in HashMap
compute(K key, BiFunction remappingFunction)
– (Since Java 8) Attempts to compute a mapping for the specified key and its current mapped value (ornull
if there is no current mapping).computeIfAbsent(K key, Function mappingFunction)
– (Since Java 8) If the specified key is not already associated with a value (or is mapped tonull
), attempts to compute its value using the given mapping function and enters it into this map unlessnull
.computeIfPresent(K key, BiFunction remappingFunction)
– (Since Java 8) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
Following example shows you how to compute or update (remapping) a value in HashMap
public class HashMapComputeDemo { public static void main(String[] args) { Map<Integer, String> hashMap = new HashMap<Integer, String>(); String msg = " King"; // put() hashMap.put(7, "Peter"); hashMap.put(5, "Philip"); hashMap.put(2, "Martin"); hashMap.put(4, null); System.out.println("Initial HashMap: " + hashMap); // Using compute(key, BiFunction) //hashMap.compute(4, (key, oldValue) -> oldValue.concat(msg));// throws Excpetion NPE hashMap.compute(4, (key, oldValue) -> oldValue==null ? msg : oldValue.concat(msg)); hashMap.compute(2, (key, oldValue) -> oldValue==null ? msg : oldValue.concat(msg)); System.out.println("HashMap using compute() => " + hashMap); // Using computeIfAbsent(key, Function) hashMap.computeIfAbsent(1, key -> "Galvin"+msg); hashMap.computeIfAbsent(2, key -> "Luther"+msg); System.out.println("HashMap using computeIfAbsent() => " + hashMap); // Using computeIfAbsent(key, BiFunction) hashMap.computeIfPresent(7, (key, oldValue) -> "Arthur"+msg); hashMap.computeIfPresent(3, (key, oldValue) -> "Nicolas"+msg); System.out.println("HashMap using computeIfPresent() => " + hashMap); } }
Output :
Initial HashMap: {2=Martin, 4=null, 5=Philip, 7=Peter} HashMap using compute() => {2=Martin King, 4= King, 5=Philip, 7=Peter} HashMap using computeIfAbsent() => {1=Galvin King, 2=Martin King, 4= King, 5=Philip, 7=Peter} HashMap using computeIfPresent() => {1=Galvin King, 2=Martin King, 4= King, 5=Philip, 7=Arthur King}
4.8. merge() method in HashMap
merge(K key, V value, BiFunction remappingFunction)
– (Since Java 8) – By its name it seems merging two maps, it doesn’t merge two maps. What merge methods does exactly is if the specified key is not already associated with a value or is associated with null
, associates it with the given value. Otherwise, replaces the value with the results of the given remapping function, or removes if the result is null
.
Following example shows you how merge method works in HashMap.
public class HashMapMergeDemo { public static void main(String[] args) { Map<Integer, String> hashMap = new HashMap<Integer, String>(); String msg = " King"; // put() hashMap.put(7, "Peter"); hashMap.put(5, "Philip"); hashMap.put(2, "Martin"); hashMap.put(4, null); System.out.println("Initial HashMap: " + hashMap); // Using merge(key, value, BiFunction) hashMap.merge(7, "Arthur", (old, given) -> given.concat(msg)); hashMap.merge(2, "Martin", (old, given) -> given.concat(msg)); hashMap.merge(4, "Luther", (old, given) -> given.concat(msg)); hashMap.merge(6, "Robert", (old, given) -> given.concat(msg)); System.out.println("HashMap using merge() => " + hashMap); } }
Output :
Initial HashMap: {2=Martin, 4=null, 5=Philip, 7=Peter} HashMap using merge() => {2=Martin King, 4=Luther, 5=Philip, 6=Robert, 7=Arthur King}
5. Conclusion
In this article we saw what is HashMap, how to create HashMap and when do we use HashMap in Java and its each method with simple demonstration examples.