Java HashMap

A HashMap is a useful data structure when you need to associate keys with values, such as when you need to maintain a mapping of names to employee IDs, or when you need to associate product codes with product descriptions. The HashMap class provides methods for inserting and retrieving key-value pairs, as well as methods for modifying and removing elements.

Here's a simple example to demonstrate the basic usage of the java.util.HashMap class:

import java.util.HashMap; public class Main { public static void main(String[] args) { // create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the HashMap map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // retrieve a value using HashMap key int val = map.get("One"); System.out.println("One's value is : " + val); // check if a key exists in the HashMap if (map.containsKey("Two")) { System.out.println("Two is in the map"); } // remove a key-value pair using a key map.remove("Three"); // iterate over the key-value pairs in the HashMap for (String key : map.keySet()) { System.out.println(key + ": " + map.get(key)); } } }
//Output One's value is : 1 Two is in the map One: 1 Two: 2

This example creates a HashMap that maps keys and values. The put method is used to add key-value pairs to the map. The get method is used to retrieve a value using a key. The containsKey method is used to check if a key exists in the map. The remove method is used to remove a key-value pair using a key. Finally, the keySet method is used to get a set of the keys in the map, and a for loop is used to iterate over the key-value pairs and print them.

What is Java hashmap

The java.util.HashMap is a class in Java that implements the Map interface. It stores key-value pairs in a hash table, allowing for constant-time (O(1)) access to individual elements based on their keys. The HashMap class uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found. This allows for efficient insertion and retrieval of elements, and also helps to ensure that the HashMap remains balanced as elements are added and removed.

Important Features of HashMap

Some of the important features of the java.util.HashMap class include:

  1. Key-Value Mapping: The HashMap stores key-value pairs, where each key is associated with a single value. This allows you to retrieve the value associated with a given key in constant time (O(1)).
  2. Hashing: The HashMap uses a hash function to compute an index into an array of buckets or slots, where the key-value pairs are stored. This allows for efficient insertion and retrieval of elements, and helps to ensure that the HashMap remains balanced as elements are added and removed.
  3. Dynamic Size: The HashMap is dynamically resizable, which means that it can grow or shrink as elements are added or removed. This makes it a useful data structure for applications that need to store a large number of elements that may change over time.
  4. Null Keys and Values: The HashMap allows for null keys and values, which can be useful in certain situations.
  5. Concurrent Access: The HashMap is not synchronized, which means that multiple threads can access it simultaneously. This can lead to data corruption if multiple threads modify the HashMap simultaneously. To overcome this, you can use the java.util.Collections.synchronizedMap(Map m) method to obtain a synchronized (thread-safe) map.
  6. Iteration: The HashMap provides methods for iterating over the key-value pairs, such as the keySet(), values(), and entrySet() methods.

How Java hashmap works?


what is java hashmap

The Java HashMap works by using a hash function to compute an index into an array of buckets or slots, where the key-value pairs are stored. The hash function takes the key as input and returns an integer value, which is used as the index into the array.

When a key-value pair is added to the HashMap, the hash function is used to compute the index for the key. If the index is already occupied, the HashMap checks the keys stored at that index to determine if the key already exists. If it does, the old value is replaced with the new HashMap value. If the key does not already exist, the key-value pair is added to the HashMap at that index.

When a value is retrieved from the HashMap, the hash function is used to compute the index for the key. The HashMap then checks the keys stored at that index to determine if the key exists. If it does, the associated value is returned. If the key does not exist in HashMap, null is returned.

The HashMap also uses a technique called rehashing to ensure that the keys are evenly distributed across the buckets. Rehashing occurs when the HashMap reaches a certain threshold of utilization, at which point the size of the HashMap is increased and the keys are rehashed to their new indices. This helps to ensure that the HashMap remains balanced and efficient as elements are added and removed.

Overall, the HashMap provides constant-time (O(1)) access to individual elements based on their keys, making it a fast and efficient data structure for storing key-value pairs in Java.

Internal Structure of HashMap

Java HashMap is implemented as an array of buckets, where each bucket is a linked list of key-value pairs. Each key-value pair is represented as a Map.Entry object, which stores the key and value, as well as a reference to the next entry in the same bucket. When you add a new entry to the HashMap, it uses the hash code of the key to determine the index of the bucket where the entry should be placed. If the bucket already contains one or more entries, the new entry is appended to the end of the linked list. To look up a value by its key, the HashMap calculates the hash code of the key and then searches the linked list at the corresponding bucket for the desired entry.

Java Hashmap Examples:

Following are some examples of using a HashMap in Java:

Creating a HashMap

HashMap<String, Integer> map = new HashMap<>();

In the above example, the HashMap is created with String keys and Integer values.

Add elements in Hashmap

Elements can be added to a java.util.HashMap using the put method:

// create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the map map.put("One", 1); map.put("Two", 2); map.put("Three", 3); System.out.println("HashMap Entries: " + map); //Output : HashMap Entries: {One=1, Two=2, Three=3}

The put method in HashMap takes two arguments: a key and a value. The key is used to look up the value in the map, and the value is the value that is associated with the key. In this example, the keys are strings (the names), and the values are integers (the ages). You can add as many key-value pairs as you want to the map, and you can look up the values using the keys later.

Remove elements from HashMap

The following example that demonstrates how to remove elements from a HashMap using the remove method:

// create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the map map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // print the map before removing an element System.out.println("Before removing: " + map); // remove an element using a key map.remove("Two"); // print the map after removing an element System.out.println("After removing: " + map);
//Output: Before removing: {One=1, Two=2, Three=3} After removing: {One=1, Three=3}

In the above example, the remove() method is used to remove a key-value pair from the map. The method takes a single argument, which is the key of the key-value pair to be removed. In this example, the key is "Two". The remove method returns the value that was associated with the key, or null if the key was not found in the map. In this example, the map is printed before and after removing an element, so you can see the effect of the remove method.

How to update a hashmap value by using key?

Following example that demonstrates how to replace elements in a HashMap using the put method:

// create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the map map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // print the map before replacing an element System.out.println("Before replacing: " + map); // replace an element using a key map.put("Two", 22); // print the map after replacing an element System.out.println("After replacing: " + map);
//Output: Before replacing: {One=1, Two=2, Three=3} After replacing: {One=1, Two=22, Three=3}

In this example, the put method is used to replace an element in the map. The HashMap method takes two arguments: a key and a value. The key is used to look up the value in the map, and the value is the value that is associated with the key. In this example, the key is "Two", and the value is 22. If the key already exists in the map, the put method will replace the existing value with the new value. In this example, the map is printed before and after replacing an element, so you can see the effect of the put method.

Search a key in HashMap

To search for a key in a java.util.HashMap, you can use the containsKey method, like this:

// create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the HashMap map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // search for a key in the map String key = "Two"; if (map.containsKey(key)) { System.out.println(key + " found in the map"); } else { System.out.println(key + " not found in the map"); } //Output: Two found in the map

In this example, the containsKey method is used to search for a key in the map. The method takes a single argument, which is the key to be searched for. In this example, the key is "Two". The containsKey method returns true if the key is found in the map, and false otherwise. In this example, the result of the search is printed to the console.

How to get Key from Value in HashMap?

To get the key associated with a value in a java.util.HashMap, you can loop over the entry set of the map and check each value.

import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { // create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the HashMap map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // search for a value in the HashMap int value = 30; String key = getKey(map, value); if (key != null) { System.out.println(key + " is associated with the value " + value); } else { System.out.println("No key is associated with the value " + value); } } private static String getKey(Map<String, Integer> map, int value) { for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue() == value) { return entry.getKey(); } } return null; } }

In this example, the getKey method is used to get the key associated with a value in the map. The method takes two arguments: the map and the value. The method loops over the entry set of the map and checks each value. If a value is found that matches the value being searched for, the method returns the associated key. In this example, the key is associated with the value 2 and is printed to the console.

Iterate over the elements in Hashmap

There are several ways to iterate over the elements of a java.util.HashMap:

Using the keySet method:

import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { // create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the HashMap map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // iterate over the keys of the HashMap for (String key : map.keySet()) { System.out.println(key + " : " + map.get(key)); } } }
//Output: One : 1 Two : 2 Three : 3

Using the entrySet method:

import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { // create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the map map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // iterate over the entries of the map for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } }
//Output: One : 1 Two : 2 Three : 3

In both examples, the elements of the map are printed to the console. Using the keySet method, the keys are looped over and the associated values are retrieved using the get method. Using the entrySet method, the entries of the map are looped over directly and the keys and values are retrieved using the getKey and getValue methods, respectively.

Get Size of Java HashMap?

To get the size of a HashMap, you can use the size method:

// create a HashMap HashMap<String, Integer> map = new HashMap<>(); // add key-value pairs to the map map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // get the size of the map int size = map.size(); // print the size of the map System.out.println("Size of the HashMap: " + size);

In this example, the size of the map is calculated using the size method and printed to the console. The output will be: Size of the HashMap: 3.

Java HashMap Methods (Summary):


how to use java hashmap

The HashMap class in Java provides several methods to manipulate a HashMap. Some of the most commonly used HashMap methods are:

  1. put(K key, V value): Adds an element to the HashMap with the specified key and value.
  2. get(Object key): Returns the value associated with the specified key in the HashMap.
  3. remove(Object key): Removes the key-value pair with the specified key from the HashMap.
  4. containsKey(Object key): Returns true if the HashMap contains the specified key, and false otherwise.
  5. containsValue(Object value): Returns true if the HashMap contains the specified value, and false otherwise.
  6. size(): Returns the number of key-value pairs in the map.
  7. isEmpty(): Returns true if the HashMap is empty, and false otherwise.
  8. clear(): Removes all the key-value pairs from the HashMap.
  9. keySet(): Returns a Set view of all the keys in the map.
  10. values(): Returns a Collection view of all the values in the HashMap.
  11. entrySet(): Returns a Set view of all the key-value pairs in the HashMap.
Note: These methods provide basic functionality for manipulating a HashMap, and there are other methods available as well, depending on your specific needs.