What is HashMap in Java?
HashMap is designed to have unique keys and corresponding values that can be retrieve any time. HashMap
allow one null
key and multiple null
values. The HashMap
class uses a
Hashtable
to implement the Map interface. This allows the execution time of basic operations, such
as get( ) and put( ), to remain constant even for large sets.
The HashMap
class is roughly equivalent to Hashtable
, except that it is unsynchronized
and permits nulls
.
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order
will remain constant over time.
Here is the topic that will cover in this post.
Java HashMap class Declaration
The HashMap
class extends AbstractMap
and implements the Map
interface. It uses a hash table to store the map. This allows the execution time of get( ) and put( ) to
remain constant even for large sets. HashMap
is a generic class that has this declaration:
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
Here, K specifies the type of keys, and V specifies the type of values.
Java HashMap features
- Java HashMap inherits AbstractMap class.
- Java HashMap implements the Map interface.
- Java HashMap permits one
null
key and multiplenull
values.- Java HashMap can not be used for primitive types, like int, char, etc. We need to use wrapper classes.
- Java HashMap is not synchronized.
- Java HashMap is not thread-safe. You can make thread-safe by doing
Map m = Collections.synchronizedMap(new HashMap(...));- Java HashMap is not an ordered collection. It does not guarantee that the order will remain constant over time.
- Java HashMap implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
- The iterators returned by all of this class's "collection view methods" are fail-fast.
- HashMap uses it’s inner class Node<K,V> to store map entries.
- Java HashMap stores entries into multiple singly linked lists, called buckets or bins. It's default number of bins is 16 and default load factor is 0.75.
- Java HashMap uses hashCode() and equals() methods on keys for get and put operations. So HashMap key object should provide good implementation of these methods. This is the reason immutable classes are better suitable for keys, for example
String
andInteger
.
Java HashMap constructors
Java HashMap have four constructors.
Constructor | Description |
---|---|
public HashMap() | Constructs an empty HashMap with default capacity (16) and the default load factor (0.75).
|
public HashMap(int initialCapacity) | Constructs an empty HashMap with the specified initial capacity and the default load factor
(0.75).
|
public HashMap(int initialCapacity, float loadFactor) | Constructs an empty HashMap with the specified initial capacity and load factor. |
public HashMap(Map<? extends K, ? extends V> m) | Constructs a new HashMap with the same mappings as the specified Map . The
HashMap is created with
default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified
Map .
|
Below code snippet show example to create HashMap instances using it's constructors.
HashMap<Integer, String> hashMap1 = new HashMap<>(); HashMap<Integer, String> hashMap2 = new HashMap<>(10); HashMap<Integer, String> hashMap3 = new HashMap<>(32, 0.85f); HashMap<Integer, String> hashMap4 = new HashMap<>(hashMap1);
Java HashMap methods
Let's have a look on HashMap
methods before Java 8.
Method | Description |
---|---|
public int size() | Returns the number of key-value mappings in this map. |
public boolean isEmpty() | Returns true if this map contains no key-value mappings. |
public V get(Object key) | Returns the value to which the specified key is mapped,
or null if this map contains no mapping for the key.
|
public boolean containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
public V put(K key, V value) | Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced. |
public void putAll(Map<? extends K, ? extends V> m) | Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map. |
public V remove(Object key) | Removes the mapping for the specified key from this map if present,
otherwise null if there was no mapping for key |
public void clear() | Removes all of the mappings from this map. The map will be empty after this call returns. |
public boolean containsValue(Object value) | Returns true if this map maps one or more keys to the specified value. |
public Set<K> keySet() | Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. |
public Collection<V> values() | Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. |
public Set<Map.Entry<K,V>> entrySet() | Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. |
public Object clone() | Returns a shallow copy of this HashMap instance: the keys and
values themselves are not cloned.
|
There are many new methods in HashMap which was introduced in Java 8
Method | Description |
---|---|
default V getOrDefault(Object key, V defaultValue) | Returns the value to which the specified key is mapped, or defaultValue if this map
contains no mapping for the key.
|
default void forEach(BiConsumer<? super K, ? super V> action) | Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. A ConcurrentModificationException will be thrown if an element is removed during the process. |
default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) | Replaces each entry's value with the result of invoking the given function on that entry
until all entries have been processed or the
function throws an exception. Exceptions thrown by the function are relayed to the caller.
|
default V putIfAbsent(K key, V value) | If the specified key is not already associated with a value (or is mapped
to null ) associates it with the given value and returns
null , else returns the current value.
|
default boolean remove(Object key, Object value) | Removes the entry for the specified key only if it is currently mapped to the specified value. |
default boolean replace(K key, V oldValue, V newValue) | If the key/value pair specified by key and oldValue is in the invoking map, the value is replaced by newValue and true is returned. Otherwise false is returned. |
default V replace(K key, V value) | Replaces the entry for the specified key only if it is currently mapped to some value. |
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) | If the specified key is not already associated with a value (or is mapped to null ),
attempts to compute its value using the given mapping function and enters it into this map unless null .
|
default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) | If key is in the map, a new value is constructed through
a call to remappingFunction and the new value replaces the old value
in the map. In this case, the new value is returned. If
the value returned by remappingFunction is null , the existing key and
value are removed from the map and null is returned.
|
default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) | Calls remappingFunction to construct a new value. If remappingFunction returns
non-null, the new key/value pair is added to the
map or any preexisting pairing is removed, and the
new value is returned. If remappingFunction returns null , any
preexisting pairing is removed, and null is returned.
|
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) | If the specified key is not already associated with a value or is
associated with null , associates it with the given non-null value.
Otherwise, replaces the associated value with the results of the given
remapping function, or removes if the result is null .
|
Example
Here is a simple program of HashMap using common methods.
package com.walking.techie; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class HashMapDemo { public static void main(String[] args) { HashMap<Integer, String> httpStatusMap = new HashMap<>(); httpStatusMap.put(100, "Continue"); httpStatusMap.put(101, "Switching Protocols"); httpStatusMap.put(102, "Processing"); httpStatusMap.put(200, "OK"); httpStatusMap.put(202, "Accepted"); httpStatusMap.put(203, "Non Authoritative Information"); httpStatusMap.put(300, "Multiple Choices"); httpStatusMap.put(302, "Moved Temporarily"); httpStatusMap.put(400, "Bad Request"); httpStatusMap.put(401, "Unauthorized"); httpStatusMap.put(405, "Method Not Allowed"); httpStatusMap.put(500, "Server Error"); httpStatusMap.put(503, "Service Unavailable"); httpStatusMap.put(507, "Insufficient Storage"); httpStatusMap.put(511, "Network Authentication Required"); // size of HashMap System.out.println("Size of the Http Status Hash Map: " + httpStatusMap.size()); // check HashMap is empty or not System.out.println("Is HashMap Empty? " + httpStatusMap.isEmpty()); // get the value for given Key System.out.println("Http message for HttpStatus code 400 is " + httpStatusMap.get(400)); System.out.println("Http message for HttpStatus code 403 is " + httpStatusMap.get(403)); // check HashMap contain mapping for given key System.out.println( "Is HashMap contain mapping for HttpStatus code 500 is " + httpStatusMap.containsKey(500)); System.out.println( "Is HashMap contain mapping for HttpStatus code 403 is " + httpStatusMap.containsKey(403)); Map<Integer, String> httpStatus = new TreeMap<>(); httpStatus.put(424, "Failed Dependency"); httpStatus.put(422, "Unprocessable Entity"); httpStatus.put(429, "Too Many Requests"); httpStatus.put(504, "Gateway Timeout"); httpStatus.put(409, "Conflict"); // copy all elements of httpStatus to httpStatusMap httpStatusMap.putAll(httpStatus); // print all the elements of the HttpStatusMap System.out.println("\n******All elements of the httpStatusMap"); for (Integer code : httpStatusMap.keySet()) { System.out .println("Http Status Code : " + code + " Http Message : " + httpStatusMap.get(code)); } // remove the mapping from the HashMap for given key System.out.println("\nValue of the removed key (507) is : " + httpStatusMap.remove(507)); // To check value is present is the HashMap System.out.println("Too Many Requests is present in HashMap : " + httpStatusMap .containsValue("Too Many Requests")); System.out.println("Upgrade Required is present in HashMap : " + httpStatusMap .containsValue("Upgrade Required")); // Get collection view of this HashMap Collection<String> httpStatusMessage = httpStatusMap.values(); System.out.println("\n *****Http Status message of the collection view*****"); for (String message : httpStatusMessage) { System.out.println("Http Status Message : " + message); } // Display key-value pair of element using EntrySet Set<Entry<Integer, String>> entrySet = httpStatusMap.entrySet(); Iterator<Entry<Integer, String>> iterator = entrySet.iterator(); System.out.println("\n *****Display Elements of the HashMap using EntrySet*****"); while (iterator.hasNext()) { Entry<Integer, String> entry = iterator.next(); System.out .println("Http Status Code : " + entry.getKey() + " Http Message : " + entry.getValue()); } // create clone of HashMap Object clonedHashMap = httpStatusMap.clone(); System.out.println("\nCloned Hash Map : \n" + clonedHashMap); // clear all elements of the HashMap httpStatusMap.clear(); System.out.println("\nSize of the httpStatusMap is " + httpStatusMap.size()); } }
Output of above program is shown below:
Size of the Http Status Hash Map: 15 Is HashMap Empty? false Http message for HttpStatus code 400 is Bad Request Http message for HttpStatus code 403 is null Is HashMap contain mapping for HttpStatus code 500 is true Is HashMap contain mapping for HttpStatus code 403 is false ******All elements of the httpStatusMap Http Status Code : 100 Http Message : Continue Http Status Code : 101 Http Message : Switching Protocols Http Status Code : 102 Http Message : Processing Http Status Code : 422 Http Message : Unprocessable Entity Http Status Code : 200 Http Message : OK Http Status Code : 424 Http Message : Failed Dependency Http Status Code : 202 Http Message : Accepted Http Status Code : 203 Http Message : Non Authoritative Information Http Status Code : 300 Http Message : Multiple Choices Http Status Code : 429 Http Message : Too Many Requests Http Status Code : 302 Http Message : Moved Temporarily Http Status Code : 400 Http Message : Bad Request Http Status Code : 401 Http Message : Unauthorized Http Status Code : 500 Http Message : Server Error Http Status Code : 405 Http Message : Method Not Allowed Http Status Code : 503 Http Message : Service Unavailable Http Status Code : 504 Http Message : Gateway Timeout Http Status Code : 409 Http Message : Conflict Http Status Code : 507 Http Message : Insufficient Storage Http Status Code : 511 Http Message : Network Authentication Required Value of the removed key (507) is : Insufficient Storage Too Many Requests is present in HashMap : true Upgrade Required is present in HashMap : false *****Http Status message of the collection view***** Http Status Message : Continue Http Status Message : Switching Protocols Http Status Message : Processing Http Status Message : Unprocessable Entity Http Status Message : OK Http Status Message : Failed Dependency Http Status Message : Accepted Http Status Message : Non Authoritative Information Http Status Message : Multiple Choices Http Status Message : Too Many Requests Http Status Message : Moved Temporarily Http Status Message : Bad Request Http Status Message : Unauthorized Http Status Message : Server Error Http Status Message : Method Not Allowed Http Status Message : Service Unavailable Http Status Message : Gateway Timeout Http Status Message : Conflict Http Status Message : Network Authentication Required *****Display Elements of the HashMap using EntrySet***** Http Status Code : 100 Http Message : Continue Http Status Code : 101 Http Message : Switching Protocols Http Status Code : 102 Http Message : Processing Http Status Code : 422 Http Message : Unprocessable Entity Http Status Code : 200 Http Message : OK Http Status Code : 424 Http Message : Failed Dependency Http Status Code : 202 Http Message : Accepted Http Status Code : 203 Http Message : Non Authoritative Information Http Status Code : 300 Http Message : Multiple Choices Http Status Code : 429 Http Message : Too Many Requests Http Status Code : 302 Http Message : Moved Temporarily Http Status Code : 400 Http Message : Bad Request Http Status Code : 401 Http Message : Unauthorized Http Status Code : 500 Http Message : Server Error Http Status Code : 405 Http Message : Method Not Allowed Http Status Code : 503 Http Message : Service Unavailable Http Status Code : 504 Http Message : Gateway Timeout Http Status Code : 409 Http Message : Conflict Http Status Code : 511 Http Message : Network Authentication Required Cloned Hash Map : {100=Continue, 101=Switching Protocols, 102=Processing, 422=Unprocessable Entity, 200=OK, 424=Failed Dependency, 202=Accepted, 203=Non Authoritative Information, 300=Multiple Choices, 429=Too Many Requests, 302=Moved Temporarily, 400=Bad Request, 401=Unauthorized, 500=Server Error, 405=Method Not Allowed, 503=Service Unavailable, 504=Gateway Timeout, 409=Conflict, 511=Network Authentication Required} Size of the httpStatusMap is 0
Iterate or Traverse over HashMap
In this link I have discussed about different ways to traverse or Iterate over the HashMap. you can find this post here.
No comments :
Post a Comment