The HashMap class in Java represents a collection that uses a hash table to map keys to values. It’s part of the Java Collections Framework and can be found in the java.util package.

Key Points

Key-Value Pairs: HashMap stores data in key-value pairs, where each key maps to a single value.

Null Allowed: HashMap allows one null key and multiple null values.

Ordering: It doesn’t guarantee any specific order for the keys or values.

Performance: Offers constant time performance for get and put methods, assuming the hash function disperses the buckets evenly.

Not Thread-Safe: HashMap isn’t synchronized. For multi-threaded environments, external synchronization or use of ConcurrentHashMap may be considered.

1. Create a HashMap and Add Key-Value Pairs to it

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, Integer> fruitsCount = new HashMap<>();

        // Add key-value pairs to the HashMap
        fruitsCount.put("Apples", 10);
        fruitsCount.put("Bananas", 20);
        fruitsCount.put("Cherries", 30);

        // Display the HashMap content
        System.out.println("Fruits count in the store:");
        for (String fruit : fruitsCount.keySet()) {
            System.out.println(fruit + ": " + fruitsCount.get(fruit));
        }

        // Adding another key-value pair
        fruitsCount.put("Dates", 15);
        System.out.println("\nAfter adding Dates:");
        for (String fruit : fruitsCount.keySet()) {
            System.out.println(fruit + ": " + fruitsCount.get(fruit));
        }
    }
}

Output:

Fruits count in the store:
Apples: 10
Bananas: 20
Cherries: 30

After adding Dates:
Apples: 10
Bananas: 20
Cherries: 30
Dates: 15

Explanation:

1. We import the HashMap class from java.util package.

2. We declare and initialize a HashMap named fruitsCount where the keys are of type String (fruit names) and values are of type Integer (count of fruits).

3. We use the put() method to add key-value pairs to the HashMap.

4. We display the content of the HashMap using a for-each loop that iterates over the key set of the HashMap using the keySet() method.

5. We then demonstrate adding another key-value pair to the HashMap and display the updated content.

2. Access Keys and Update Their Associated Value in a HashMap

import java.util.HashMap;

public class HashMapAccessExample {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, Integer> studentMarks = new HashMap<>();
        studentMarks.put("Rahul", 85);
        studentMarks.put("Priya", 90);
        studentMarks.put("Ankit", 78);

        // Check if the HashMap is empty
        System.out.println("Is the HashMap empty? " + studentMarks.isEmpty());

        // Find the size of the HashMap
        System.out.println("Size of the HashMap: " + studentMarks.size());

        // Check if a key exists
        System.out.println("Does key &apos;Rahul&apos; exist? " + studentMarks.containsKey("Rahul"));
        System.out.println("Does key &apos;Sandeep&apos; exist? " + studentMarks.containsKey("Sandeep"));

        // Check if a value exists
        System.out.println("Does value 90 exist? " + studentMarks.containsValue(90));
        System.out.println("Does value 100 exist? " + studentMarks.containsValue(100));

        // Get the value associated with a key
        System.out.println("Marks of Rahul: " + studentMarks.get("Rahul"));

        // Modify the value associated with a key
        studentMarks.put("Rahul", 88);
        System.out.println("Updated marks of Rahul: " + studentMarks.get("Rahul"));
    }
}

Output:

Is the HashMap empty? false
Size of the HashMap: 3
Does key 'Rahul' exist? true
Does key 'Sandeep' exist? false
Does value 90 exist? true
Does value 100 exist? false
Marks of Rahul: 85
Updated marks of Rahul: 88

Explanation:

1. We declare and initialize a HashMap named studentMarks where keys are of type String (student names) and values are of type Integer (marks of students).

2. We check if the HashMap is empty using the isEmpty() method.

3. We find the size of the HashMap using the size() method.

4. We check if certain keys exist in the HashMap using the containsKey() method.

5. We check if certain values exist in the HashMap using the containsValue() method.

6. We retrieve the value associated with a particular key using the get() method.

7. We modify the value associated with a particular key using the put() method. If the key already exists, its value will be overwritten by the new value provided.

3. Remove Keys from a HashMap

import java.util.HashMap;

public class HashMapRemoveExample {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, Integer> studentMarks = new HashMap<>();
        studentMarks.put("Rahul", 85);
        studentMarks.put("Priya", 90);
        studentMarks.put("Ankit", 78);

        // Display original HashMap
        System.out.println("Original HashMap: " + studentMarks);

        // Remove a key from the HashMap
        studentMarks.remove("Rahul");
        System.out.println("After removing key &apos;Rahul&apos;: " + studentMarks);

        // Remove a key only if it is associated with a given value
        studentMarks.remove("Ankit", 80); // This won&apos;t remove "Ankit" as the value is not 80
        System.out.println("After trying to remove &apos;Ankit&apos; with value 80: " + studentMarks);

        studentMarks.remove("Ankit", 78); // This will remove "Ankit" as the value is 78
        System.out.println("After removing &apos;Ankit&apos; with value 78: " + studentMarks);
    }
}

Output:

Original HashMap: {Rahul=85, Priya=90, Ankit=78}
After removing key 'Rahul': {Priya=90, Ankit=78}
After trying to remove 'Ankit' with value 80: {Priya=90, Ankit=78}
After removing 'Ankit' with value 78: {Priya=90}

Explanation:

1. We declare and initialize a HashMap named studentMarks where keys are of type String (student names) and values are of type Integer (marks of students).

2. We display the original HashMap for reference.

3. We remove a key using the remove(Object key) method, which removes the specified key and its associated value.

4. We attempt to remove a key based on a specific value using the `remove(Object key, Object value

4. Obtain the entrySet, keySet, and values from a HashMap

import java.util.HashMap;
import java.util.Set;
import java.util.Collection;
import java.util.Map.Entry;

public class HashMapViewsExample {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, String> countryCapital = new HashMap<>();
        countryCapital.put("India", "New Delhi");
        countryCapital.put("France", "Paris");
        countryCapital.put("USA", "Washington, D.C.");

        // Obtain and display entrySet
        Set<Entry<String, String>> entrySet = countryCapital.entrySet();
        System.out.println("entrySet: " + entrySet);

        // Obtain and display keySet
        Set<String> keySet = countryCapital.keySet();
        System.out.println("keySet: " + keySet);

        // Obtain and display values
        Collection<String> values = countryCapital.values();
        System.out.println("values: " + values);
    }
}

Output:

entrySet: [India=New Delhi, France=Paris, USA=Washington, D.C.]
keySet: [India, France, USA]
values: [New Delhi, Paris, Washington, D.C.]

Explanation:

1. We declare and initialize a HashMap named countryCapital where keys and values are of type String (country names and their respective capitals).

2. We obtain the entrySet from the map using the entrySet() method. This method returns a Set view of the mappings (key-value pairs) in the HashMap.

3. We obtain the keySet from the map using the keySet() method. This method returns a Set view of the keys in the HashMap.

4. We obtain the values from the map using the values() method. This method returns a Collection view of the values in the HashMap.

5. Iterate over a HashMap in Different Ways

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class HashMapIterationExample {
    public static void main(String[] args) {
        HashMap<String, Integer> studentGrades = new HashMap<>();
        studentGrades.put("Rohan", 90);
        studentGrades.put("Priya", 85);
        studentGrades.put("Anil", 88);

        // 1. Iterating using Java 8 forEach and lambda expression
        studentGrades.forEach((key, value) -> System.out.println("Student: " + key + ", Grade: " + value));

        // 2. Iterating over the HashMap’s entrySet using iterator()
        Iterator<Entry<String, Integer>> iterator = studentGrades.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, Integer> entry = iterator.next();
            System.out.println("Student: " + entry.getKey() + ", Grade: " + entry.getValue());
        }

        // 3. Iterating over the HashMap’s entrySet using Java 8 forEach and lambda expression
        studentGrades.entrySet().forEach(entry -> {
            System.out.println("Student: " + entry.getKey() + ", Grade: " + entry.getValue());
        });

        // 4. Iterating over the HashMap’s entrySet using simple for-each loop
        for (Entry<String, Integer> entry : studentGrades.entrySet()) {
            System.out.println("Student: " + entry.getKey() + ", Grade: " + entry.getValue());
        }

        // 5. Iterating over the HashMap’s keySet
        for (String student : studentGrades.keySet()) {
            System.out.println("Student: " + student + ", Grade: " + studentGrades.get(student));
        }
    }
}

Output:

Student: Rohan, Grade: 90
Student: Priya, Grade: 85
Student: Anil, Grade: 88
... (This will repeat for each iteration method)

Explanation:

1. Using the forEach method introduced in Java 8 and a lambda expression, we can iterate directly over the HashMap.

2. Using an Iterator to traverse through the entrySet of the HashMap.

3. Utilizing Java 8's forEach method with the entrySet provides another way to iterate over the key-value pairs.

4. A simple for-each loop with the entrySet lets us loop through each key-value pair.

5. By iterating over the keySet, we only access the keys and then get the corresponding value from the map using the get() method.

6. Using HashMap with User-Defined Objects – Student

// Define the Student class with attributes: id and name
public class Student {
    private int id;
    private String name;

    // Constructor
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters and setters
    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    // Override the toString method for easy printing
    @Override
    public String toString() {
        return "Student{" + "id=" + id + ", name=&apos;" + name + &apos;\&apos;&apos; + &apos;}&apos;;
    }

    public static void main(String[] args) {
        // Create a HashMap with Integer as the key type and Student as the value type
        HashMap<Integer, Student> studentMap = new HashMap<>();

        // Add Student objects to the HashMap
        studentMap.put(1, new Student(1, "Rohit"));
        studentMap.put(2, new Student(2, "Priya"));
        studentMap.put(3, new Student(3, "Aman"));

        // Print the HashMap
        for (Map.Entry<Integer, Student> entry : studentMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Output:

Key: 1, Value: Student{id=1, name='Rohit'}
Key: 2, Value: Student{id=2, name='Priya'}
Key: 3, Value: Student{id=3, name='Aman'}

Explanation:

1. We first define a Student class with attributes id and name.

2. Within the main method, we initialize a HashMap with Integer as the key (representing the student ID) and Student as the value.

3. We then add three student objects to the HashMap using the put method.

4. Finally, we iterate over the HashMap and print the key-value pairs.

7. Synchronize Access to Java HashMap

import java.util.HashMap;
import java.util.Collections;
import java.util.Map;

public class SyncHashMapExample {

    public static void main(String[] args) {
        // Step 1: Create a HashMap
        Map<String, String> map = new HashMap<>();

        // Step 2: Populate the HashMap
        map.put("1", "One");
        map.put("2", "Two");
        map.put("3", "Three");

        // Step 3: Synchronize the HashMap
        Map<String, String> synchronizedMap = Collections.synchronizedMap(map);

        // Step 4: Show the map content
        System.out.println("Synchronized map content: " + synchronizedMap);
    }
}

Output:

Synchronized map content: {1=One, 2=Two, 3=Three}

Explanation:

1. A basic HashMap is created and populated with some key-value pairs.

2. The HashMap is synchronized using Collections.synchronizedMap(). This returns a synchronized (thread-safe) map backed by the specified map.

3. The content of the synchronized map is printed to the console.

8. Phone Directory with HashMap

import java.util.HashMap;
import java.util.Map;

public class PhoneDirectory {

    public static void main(String[] args) {
        // Step 1: Create a HashMap to store names as keys and phone numbers as values
        Map<String, String> phoneDirectory = new HashMap<>();

        // Step 2: Add entries to the phone directory
        phoneDirectory.put("John Doe", "123-456-7890");
        phoneDirectory.put("Jane Smith", "987-654-3210");
        phoneDirectory.put("Robert Brown", "456-789-0123");

        // Step 3: Lookup a phone number by name
        String nameToSearch = "Jane Smith";
        String phoneNumber = phoneDirectory.get(nameToSearch);

        // Step 4: Display the result
        System.out.println(nameToSearch + "&apos;s Phone Number: " + phoneNumber);
    }
}

Output:

Jane Smith's Phone Number: 987-654-3210

Explanation:

1. We use a HashMap where names (String) are the keys and phone numbers (also String) are the values.

2. We add three entries to our phone directory using the put method.

3. We then look up a phone number using the get method.

4. Finally, we display the retrieved phone number for the given name.

Conclusion

In this tutorial, you learned what is a HashMap, key points about HashMap, how to create a HashMap, how to add new key-value pairs to a HashMap, how to remove keys from a HashMap, how to iterate over a HashMap, how to synchronize a HashMap.