HashMap

What is a Java HashMap

In Java, the HashMap data structure is used to store items in key/value pairs. It is a popular Collection class that implements the Map interface and is based on a hash table data structure.A HashMap allows you to access items using their unique keys, which are used to associate each value in the map.The HashMap class in Java extends the AbstractMap class, which provides the functionality of a hash table-based implementation

What are the features of a HashMap in Java?

  1. Key-Value Pair Storage: Java HashMap stores values based on their corresponding keys in a key-value pair format.
  2. Unique Keys: Java HashMap ensures that it contains only unique keys, avoiding duplicates.
  3. Null Key and Multiple Null Values: Java HashMap allows for the storage of one null key and multiple null values.
  4. Non-Synchronized: Java HashMap is non-synchronized, making it not inherently thread-safe.
  5. Unordered Collection: Java HashMap does not maintain any specific order of elements; the data is unordered.
  6. Default Initial Capacity: The default initial capacity of the Java HashMap class is 16.
  7. Load Factor: The Java HashMap class has a load factor of 0.75.
  8. Key/Value Pair Storage: Items in a Java HashMap are stored in key/value pairs.
  9. No Preservation of Insertion Order: The items in a Java HashMap are not ordered; their insertion order is not preserved.
  10. Handling Duplicate Keys: When duplicate keys are present, the last one added will override the previous one(s).
  11. Wrapper Classes: Java HashMap uses wrapper classes to specify data types instead of primitive data types.
When working with HashMaps in Java, we utilize these wrapper classes to store and manipulate elements in the key-value pairs.
Wrapper Classes Primitive Data Types
Integer int
Character char
Float float
Byte byte
Short short
Long long
Double double
Boolean boolean

This is the syntax for creating a new HashMap.

import java.util.HashMap;

HashMap<KeyDataType, ValueDataType> HashMapName = new HashMap<>();

We should explain some of the key terms in the syntax above.
  1. import java.util.HashMap; :-Imports the HashMap class from the java.util package, enabling the use of HashMap in the code.
  2. HashMap<KeyDataType, ValueDataType>: Declares a new HashMap variable called HashMapName with generic types KeyDataType and ValueDataType. Replace KeyDataType and ValueDataType with the desired data types for keys and values, respectively.
  3. HashMapName = new HashMap<>(); :- Initializes a new instance of HashMap and assigns it to the HashMapName variable.

After this code, you have a new and empty HashMap called HashMapName ready to store key-value pairs with the specified data types. You can use various methods provided by the HashMap class, such as put(), get(), containsKey(), etc., to manipulate and access the data in the HashMap.

Here are some common HashMap methods in Java categorized by their operations:

  1. Adding and Updating Elements:
    • put(Key key, Value value): Adds a key-value pair to the HashMap. If the key already exists, the value is updated.
  2. Retrieving Elements:
    • get(Key key): Retrieves the value associated with the specified key. Returns null if the key is not found.
  3. Removing Elements:
    • remove(Key key): Removes the key-value pair associated with the given key from the HashMap.
  4. Checking Existence:
    • containsKey(Key key): Checks if the HashMap contains the specified key. Returns true if found, false otherwise.
    • containsValue(Value value): Checks if the HashMap contains the specified value. Returns true if found, false otherwise.
  5. Size and Status:
    • size(): Returns the number of key-value pairs present in the HashMap.
    • isEmpty(): Checks if the HashMap is empty. Returns true if no elements are present, false otherwise.
  6. Retrieving Keys and Values:
    • keySet(): Returns a Set containing all the keys present in the HashMap.
    • values(): Returns a Collection containing all the values present in the HashMap.
    • entrySet(): Returns a Set containing all the key-value pairs (Map.Entry) present in the HashMap.
  7. Bulk Operations:
    • putAll(Map<? extends Key, ? extends Value> map): Copies all the key-value pairs from the specified map into the HashMap.
  8. Clearing the HashMap:
    • clear(): Removes all the key-value pairs from the HashMap, making it empty.

Example of  How to add and update elements in a HashMap in Java:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap to store student names and their corresponding ages
        HashMap<String, Integer> studentAges = new HashMap<>();

        // Adding elements to the HashMap using the put() method
        studentAges.put("Alice", 25);
        studentAges.put("Bob", 22);
        studentAges.put("Charlie", 23);

        // Display the initial HashMap
        System.out.println("Initial HashMap: " + studentAges);

        // Updating an existing element in the HashMap
        studentAges.put("Bob", 23); // Bob's age is updated from 22 to 23

        // Display the updated HashMap
        System.out.println("Updated HashMap: " + studentAges);
    }
}

Output:

Initial HashMap: {Alice=25, Bob=22, Charlie=23}
Updated HashMap: {Alice=25, Bob=23, Charlie=23}

Here’s a detailed explanation of each part of the code:

  1. A HashMap named studentAges is created with keys of type String (representing student names) and values of type Integer (representing student ages).
  2. Elements are added to the studentAges HashMap using the put() method. Three key-value pairs are added:
    • Key: “Alice”, Value: 25
    • Key: “Bob”, Value: 22
    • Key: “Charlie”, Value: 23
  3. The System.out.println(“Initial HashMap: ” + studentAges) statement is used to print the content of the studentAges HashMap before any updates.
  4. The studentAges.put(“Bob”, 23) statement updates the age of “Bob” from 22 to 23. Since “Bob” already exists in the HashMap, the put() method replaces the existing value (22) with the new value (23) associated with the same key.
  5. The System.out.println(“Updated HashMap: ” + studentAges) statement is used to print the content of the studentAges HashMap after the update. Output: Initial HashMap: {Alice=25, Bob=22, Charlie=23} .Updated HashMap: {Alice=25, Bob=23, Charlie=23}

The output shows the content of the studentAges HashMap before and after the update. The HashMap preserves the keys (student names) but allows updating the values (student ages) associated with those keys. In this case, “Bob” initially had an age of 22, but it was updated to 23. The other elements remain unchanged.

Note: In a HashMap, we can update the value associated with a specific key using the replace(Key key, Value newValue) method. This method replaces the existing value with the new value provided for the given key. If the key is not present in the HashMap, the replace operation will not have any effect.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap to store student names and their corresponding scores
        HashMap<String, Integer> studentScores = new HashMap<>();

        // Adding elements to the HashMap using the put() method
        studentScores.put("Alice", 85);
        studentScores.put("Bob", 92);
        studentScores.put("Charlie", 78);

        // Displaying the initial HashMap
        System.out.println("Initial HashMap: " + studentScores);

        // Update Bob's score to 88 using the replace() method
        studentScores.replace("Bob", 88);

        // Displaying the updated HashMap
        System.out.println("Updated HashMap: " + studentScores);
    }
}

Output:

Initial HashMap: {Alice=85, Bob=92, Charlie=78}
Updated HashMap: {Alice=85, Bob=88, Charlie=78}

Example of  How to access elements in a HashMap in Java:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap to store employee names and their corresponding salaries
        HashMap<String, Integer> employeeSalaries = new HashMap<>();

        // Adding elements to the HashMap using the put() method
        employeeSalaries.put("John", 40000);
        employeeSalaries.put("Emma", 35000);
        employeeSalaries.put("Michael", 50000);

        // Accessing items from the HashMap using the get() method
        int johnSalary = employeeSalaries.get("John");
        int emmaSalary = employeeSalaries.get("Emma");

        // Displaying the retrieved values
        System.out.println("John's salary: $" + johnSalary);
        System.out.println("Emma's salary: $" + emmaSalary);
    }
}

Output:

John’s salary: $40000
Emma’s salary: $35000

Here’s a detailed explanation of each part of the code:

In this code snippet, we are using a HashMap named employeeSalaries to store employee names (as keys) and their corresponding salaries (as values). Let’s break down the code step-by-step:

  1. HashMap<String, Integer> employeeSalaries = new HashMap<>(); :- This line creates a new HashMap called employeeSalaries, where the keys are of type String (representing employee names) and the values are of type Integer (representing their salaries).
  2. put(“John”, 40000); :- This line adds a key-value pair to the employeeSalaries HashMap. It associates the key “John” with the value 40000, indicating that John’s salary is $40,000.
  3. put(“Emma”, 35000); :- This line adds another key-value pair to the HashMap, representing Emma’s salary of $35,000.
  4. put(“Michael”, 50000); :- This line adds a third key-value pair to the HashMap, representing Michael’s salary of $50,000.
  5. int johnSalary = employeeSalaries.get(“John”); :- This line uses the get() method to access the salary of “John” from the employeeSalaries The get(“John”) call returns the value associated with the key “John,” which is 40000, and assigns it to the variable johnSalary.
  6. int emmaSalary = employeeSalaries.get(“Emma”); :- This line does the same for “Emma.” The get(“Emma”) call retrieves the value associated with the key “Emma,” which is 35000, and assigns it to the variable emmaSalary.
  7. System.out.println(“John’s salary: $” + johnSalary); :- This line prints John’s salary to the console using System.out.println(). The + operator is used to concatenate the string “John’s salary: $” with the value stored in the johnSalary variable. As a result, the output will display “John’s salary: $40000.”
  8. System.out.println(“Emma’s salary: $” + emmaSalary); :- This line does the same for Emma’s salary, printing it to the console. The output will display “Emma’s salary: $35000.”

Example of  How to Delete elements in a HashMap in Java:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap to store student names and their corresponding scores
        HashMap<String, Integer> studentScores = new HashMap<>();

        // Adding elements to the HashMap using the put() method
        studentScores.put("Alice", 85);
        studentScores.put("Bob", 92);
        studentScores.put("Charlie", 78);

        // Displaying the initial HashMap
        System.out.println("Initial HashMap: " + studentScores);

        // Deleting Bob's score from the HashMap using the remove() method
        studentScores.remove("Bob");

        // Displaying the updated HashMap
        System.out.println("Updated HashMap: " + studentScores);
    }
}

Output:

Initial HashMap: {Alice=85, Bob=92, Charlie=78}
Updated HashMap: {Alice=85, Charlie=78}

Here’s a detailed explanation of each part of the code:

In this code snippet, we use a HashMap named studentScores to store student names (as keys) and their corresponding scores (as values). Let’s go through the code step-by-step:

  1. HashMap<String, Integer> studentScores = new HashMap<>(); :- This line creates a new HashMap called studentScores, where the keys are of type String (representing student names) and the values are of type Integer (representing their scores).
  2. put(“Alice”, 85); :- This line adds a key-value pair to the studentScores HashMap. It associates the key “Alice” with the value 85, indicating that Alice’s score is 85.
  3. put(“Bob”, 92); :- This line adds another key-value pair to the HashMap, representing Bob’s score of 92.
  4. put(“Charlie”, 78); :- This line adds a third key-value pair to the HashMap, representing Charlie’s score of 78.
  5. System.out.println(“Initial HashMap: ” + studentScores); :- This line prints the initial content of the studentScores HashMap to the console. The output will show all the key-value pairs in the format {key=value, key=value, …}.
  6. remove(“Bob”); :- This line uses the remove() method to delete the key-value pair associated with the key “Bob” from the studentScores HashMap. After this line, the entry for Bob and his score 92 will be removed from the HashMap.
  7. System.out.println(“Updated HashMap: ” + studentScores); :- This line prints the updated content of the studentScores HashMap to the console. After removing Bob’s entry, the output will show the remaining key-value pairs.
Below is an example of a HashMap in Java with some of the common methods used to manipulate and access its elements:
import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap to store employee names and their corresponding salaries
        HashMap<String, Integer> employeeSalaries = new HashMap<>();

        // Adding elements to the HashMap using the put() method
        employeeSalaries.put("Alice", 40000);
        employeeSalaries.put("Bob", 35000);
        employeeSalaries.put("Charlie", 50000);

        // Displaying the HashMap
        System.out.println("Initial HashMap: " + employeeSalaries);

        // Checking if a key exists in the HashMap using containsKey() method
        boolean containsKey = employeeSalaries.containsKey("Bob");
        System.out.println("Contains key 'Bob': " + containsKey);

        // Checking if a value exists in the HashMap using containsValue() method
        boolean containsValue = employeeSalaries.containsValue(35000);
        System.out.println("Contains value '35000': " + containsValue);

        // Accessing a value using the get() method
        int charlieSalary = employeeSalaries.get("Charlie");
        System.out.println("Charlie's salary: $" + charlieSalary);

        // Updating a value using the replace() method
        employeeSalaries.replace("Bob", 38000);

        // Displaying the updated HashMap
        System.out.println("Updated HashMap: " + employeeSalaries);

        // Removing an entry using the remove() method
        employeeSalaries.remove("Alice");

        // Displaying the final HashMap
        System.out.println("Final HashMap: " + employeeSalaries);

        // Getting the size of the HashMap using size() method
        int size = employeeSalaries.size();
        System.out.println("Size of the HashMap: " + size);

        // Clearing the HashMap using clear() method
        employeeSalaries.clear();

        // Checking if the HashMap is empty using isEmpty() method
        boolean isEmpty = employeeSalaries.isEmpty();
        System.out.println("Is HashMap empty? " + isEmpty);
    }
}
Output:
Initial HashMap: {Alice=40000, Bob=35000, Charlie=50000}
Contains key ‘Bob’: true
Contains value ‘35000’: true
Charlie’s salary: $50000
Updated HashMap: {Alice=40000, Bob=38000, Charlie=50000}
Final HashMap: {Bob=38000, Charlie=50000}
Size of the HashMap: 2
Is HashMap empty? false

Explanation of this code:

This code demonstrates various operations on a HashMap named employeeSalaries, which stores employee names (keys) and their corresponding salaries (values) as key-value pairs. Here’s an explanation of the operations:

  1. Adding elements: The code adds three key-value pairs to the employeeSalaries HashMap using the put() method.
  2. Displaying the HashMap: The initial content of the employeeSalaries HashMap is displayed using System.out.println().
  3. Checking if a key exists: It checks if the HashMap contains the key “Bob” using the containsKey() method.
  4. Checking if a value exists: It checks if the HashMap contains the value 35000 using the containsValue() method.
  5. Accessing a value: It retrieves the value associated with the key “Charlie” using the get() method.
  6. Updating a value: It updates the salary of “Bob” from 35000 to 38000 using the replace() method.
  7. Displaying the updated HashMap: The employeeSalaries HashMap after the value update is displayed.
  8. Removing an entry: It removes the entry for “Alice” from the HashMap using the remove() method.
  9. Displaying the final HashMap: The employeeSalaries HashMap after removing “Alice” is displayed.
  10. Getting the size of the HashMap: The number of key-value pairs in the HashMap is obtained using the size() method.
  11. Clearing the HashMap: All entries in the employeeSalaries HashMap are removed using the clear() method.
  12. Checking if the HashMap is empty: It checks if the HashMap is empty using the isEmpty() method.

The output will vary depending on the execution and order of operations. The program should display results such as “Contains key ‘Bob’: true” and “Charlie’s salary: $50000” along with other relevant information about the HashMap.

Visited 1 times, 1 visit(s) today

Comments are closed.

Close