Java HashMapJava HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc. HashMap class is found in the java.util package. HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and implements the Map interface. Points to Remember
Properties of HashMap
Hierarchy of HashMap ClassAs shown in the above figure, the HashMap class extends the AbstractMap class and implements the Map interface. HashMap Class DeclarationLet's see the declaration for java.util.HashMap class. HashMap Class ParametersLet's see the Parameters for java.util.HashMap class.
Constructors of Java HashMap Class
Methods of Java HashMap Class
Java HashMap ExampleLet's see a simple example of HashMap to store key and value pair. HashMapExample1.java Test it NowOutput: Iterating Hashmap... 1 Mango 2 Apple 3 Banana 4 Grapes Explanation The provided Java code initializes a HashMap named map, which is parameterized to accept Integer keys and String values. Four key-value pairs are then added to the HashMap using the put method, associating integers 1 to 4 with corresponding fruit names ('Mango', 'Apple', 'Banana', and 'Grapes'). Subsequently, a loop iterates over the entries of the HashMap using the entrySet() method, printing each key-value pair to the console. No Duplicate Key on HashMapWe cannot store duplicate keys in HashMap. However, if we try to store a duplicate key with another value, it will replace the value. Because of this behavior, HashMaps are guaranteed to retain a one-to-one mapping between keys and values, where each key and value is uniquely identified. It's also important to remember that HashMaps permit null values, but only one null key may exist. Within the HashMap data structure, fast key-value pair retrieval and manipulation are made possible by this unique restriction on keys. HashMapExample2.java Test it NowOutput: Iterating Hashmap... 1 Grapes 2 Apple 3 Banana Explanation The Java code that is provided initializes a hash map with the name map, mapping String values to Integer keys. Using the put method, four key-value pairs-each representing a fruit and its matching identifier-are added to the HashMap. Interestingly, the code replaces the value ("Mango") associated with key 1 by attempting to introduce a duplicate key (1) with a different value ("Grapes"). Java HashMap Example to Add ElementsThere are the following ways to add elements in HashMap: 1. Using put() Method: A key-value pair is inserted into the HashMap using the put() method. The new value is overwritten in the related value if the specified key already exists. 2. Using putIfAbsent() Method: The putIfAbsent() method only adds a key-value pair to the HashMap in the event that the given key isn't already there. 3. Using putAll() Method: Copy every key-value pair from one HashMap to another using the putAll() method. All of the components from the designated map are added to the active map. These techniques give programmers in Java the ability to add entries to HashMaps with flexibility, facilitating the effective manipulation and arrangement of key-value data structures. Let's implement all the above methods in a Java program. HashMap1.java Output: Initial list of elements: {} After invoking put() method 100 Amit 101 Vijay 102 Rahul After invoking putIfAbsent() method 100 Amit 101 Vijay 102 Rahul 103 Gaurav After invoking putAll() method 100 Amit 101 Vijay 102 Rahul 103 Gaurav 104 Ravi Explanation The Java code that is provided creates a hash map called hm with key-value pairs of String and Integer, respectively. This HashMap is expanded with new elements by utilising the put() method. Then, if the given key is not already linked to a value, the putIfAbsent() function is used to add a key-value pair. Next, all of the components from hm are added to map using the putAll() method, which creates a new HashMap with the name map. Java HashMap Example to Remove Elements1. remove(Object key): If the mapping for the given key exists in the HashMap, it is removed. gives back the value that corresponds to the key, or null if the key is absent. 2. remove(Object key, Object value): If the supplied key is currently mapped to the specified value, only then is the entry for that key removed. Returns false otherwise and true if the removal was successful. 3. clear(): Empties the HashMap by removing all key-value pairs. HashMap2.java Output: Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav} Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav} Updated list of elements: {102=Rahul, 103=Gaurav} Updated list of elements: {103=Gaurav} Explanation The Java code that is provided initialises a hash map called "map" with integer keys and string values. It then uses the put() function to fill the map with many key-value pairs. The remove() function is then used to demonstrate various removal scenarios: initially, an item is removed based on a specific key (map.remove(100)), then a value-based entry is removed (map.remove(101)), and lastly, an entry is removed based on both a key and a value (map.remove(102, "Rahul")). The updated list of entries in the hash map is produced to reflect the modifications made following each removal operation. Java HashMap Example to Replace Elements
HashMap3.java Output: Initial list of elements: 100 Amit 101 Vijay 102 Rahul Updated list of elements: 100 Amit 101 Vijay 102 Gaurav Updated list of elements: 100 Amit 101 Ravi 102 Gaurav Updated list of elements: 100 Ajay 101 Ajay 102 Ajay Explanation The Java code that is provided initialises a hash map called "hm" with multiple key-value pairs and, integer keys and String values. After that, various techniques for swapping out elements in the hash map are shown. First, it substitutes "Gaurav" for the value linked to key 102 using the replace(K key, V value) method. The value associated with key 101 is then changed from "Vijay" to "Ravi" using the replace(K key, V oldValue, V newValue) method. Lastly, it replaces every value in the HashMap with "Ajay" by using the replaceAll(BiFunction<K, V, V> function) method. Following every replacement operation, the HashMap's updated element list is printed. Difference Between HashSet and HashMapHashSet contains only values, whereas HashMap contains an entry(key and value).
Let's see Java HashMap program. MapExample.java Test it NowOutput: 1 Details: 101 Let us C Yashwant Kanetkar BPB 8 2 Details: 102 Data Communications and Networking Forouzan Mc Graw Hill 4 3 Details: 103 Operating System Galvin Wiley 6 Explanation The Java code that is provided shows how to store and retrieve instances of the class Book using a hash map. It begins with defining the Book class, which has a constructor to initialise the attributes id, name, author, publisher, and quantity. A hash map with integer keys and book values is built in the MapExample class. Using distinct integer keys, multiple Book objects are constructed and appended to the hash map. Next, a for-each loop over the entry set is used by the code to iterate through the HashMap. Each entry's key and matching Book object are retrieved, and the details of each Book-including its id, name, author, publisher, and quantity-are printed out. ConclusionTo sum up, the Java HashMap class offers a strong tool for effectively storing key-value pairs. When the hash function equally distributes elements throughout the buckets, it offers constant-time performance for simple operations like put and get. It facilitates the quick insertion, retrieval, and removal of elements based on keys. HashMaps offers flexibility and scalability for managing big datasets thanks to features like load factor control, automatic resizing, and collision handling via independent chaining. It's crucial to remember that hash maps lack synchronisation and are, therefore, inappropriate for concurrent access in the absence of external synchronisation. Hash maps are a basic data structure in Java that provides a flexible way to handle key-value mappings and associative arrays in a variety of programming contexts. Related TopicsWorking of HashMap in Java | How HashMap Works Difference between HashMap and Hashtable Difference between HashSet and HashMap Difference between HashMap and TreeMap Next TopicHow HashMap works |