HashMap Methods in Java

In this article, you will learn important Java HashMap methods with examples.

put() Method

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

Here is an example of using the put() method in a HashMap:
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        System.out.println(map);
    }
}
Output:
{Apple=10, Banana=30, Orange=20}

putAll() Method

The putAll() method is used to copy all of the mappings from the specified map to this map.

Here is an example of using the putAll() method in a HashMap:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Creating two HashMap objects
        HashMap<String, Integer> studentMarks1 = new HashMap<>();
        HashMap<String, Integer> studentMarks2 = new HashMap<>();

        // Using put() method to add key-value pairs to first HashMap
        studentMarks1.put("Alice", 85);
        studentMarks1.put("Bob", 90);

        // Using put() method to add key-value pairs to second HashMap
        studentMarks2.put("Charlie", 95);
        studentMarks2.put("David", 80);

        // Displaying the initial HashMaps
        System.out.println("Initial HashMap 1: " + studentMarks1);
        System.out.println("Initial HashMap 2: " + studentMarks2);

        // Using putAll() method to put all mappings from second HashMap to the first
        studentMarks1.putAll(studentMarks2);

        // Displaying the updated HashMaps
        System.out.println("Updated HashMap 1: " + studentMarks1);
        System.out.println("Unchanged HashMap 2: " + studentMarks2);
    }
}

Output:

Initial HashMap 1: {Alice=85, Bob=90}
Initial HashMap 2: {Charlie=95, David=80}
Updated HashMap 1: {Alice=85, Bob=90, Charlie=95, David=80}
Unchanged HashMap 2: {Charlie=95, David=80}

In this example, we create two HashMap objects named studentMarks1 and studentMarks2 that map students' names (Strings) to their marks (Integers). We use the put() method to add different key-value pairs to each HashMap. Then, we use the putAll() method to put all mappings from studentMarks2 to studentMarks1. This does not affect studentMarks2. After each putAll() operation, we print out the contents of both HashMaps.

get() Method

The get() method takes the key as an argument and returns the corresponding value. To access elements in a HashMap, you can use the get() method:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        // Access the value corresponding to the key "Apple"
        Integer appleValue = map.get("Apple");
        System.out.println("Value for 'Apple': " + appleValue);

        // Access the value corresponding to the key "Orange"
        Integer orangeValue = map.get("Orange");
        System.out.println("Value for 'Orange': " + orangeValue);

        // Access the value corresponding to the key "Banana"
        Integer bananaValue = map.get("Banana");
        System.out.println("Value for 'Banana': " + bananaValue);
    }
}
Output:
Value for 'Apple': 10
Value for 'Orange': 20
Value for 'Banana': 30
This output shows the values associated with the keys "Apple", "Orange", and "Banana" in the HashMap. 

Note: If you attempt to access a key that does not exist in the HashMap using the get method, it will return null.

remove() Method

To remove an element from the HashMap, use the remove() method. The remove() method removes the mapping for a key from this map if it is present.

Here is the complete example:
import java.util.HashMap;

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

        // Add key-value pairs to the HashMap
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        System.out.println("Original HashMap: " + map);

        // Remove the key-value pair with key "Apple"
        map.remove("Apple");

        System.out.println("HashMap after removing 'Apple': " + map);

        // Remove the key-value pair with key "Orange"
        map.remove("Orange");

        System.out.println("HashMap after removing 'Orange': " + map);
    }
}
This program creates a HashMap, adds some key-value pairs to it, and then removes some of these pairs. The remove() method takes a key as an argument and removes the corresponding key-value pair from the HashMap. 

When you run this program, you should see the following output:

Original HashMap: {Orange=20, Banana=30, Apple=10}
HashMap after removing 'Apple': {Orange=20, Banana=30}
HashMap after removing 'Orange': {Banana=30}

size() Method

We can get the size of the HashMap using the size() method.

Here's a simple example of how to get the size of a HashMap in Java:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Creating a HashMap object
        HashMap<String, String> map = new HashMap<>();

        // Adding key-value pairs to the map
        map.put("Apple", "Red");
        map.put("Orange", "Orange");
        map.put("Banana", "Yellow");
        map.put("Mango", "Yellow");

        System.out.println("Original HashMap: " + map);

        // Getting the size of the map
        int size = map.size();

        System.out.println("Size of the HashMap: " + size);
    }
}
Output:
Original HashMap: {Mango=Yellow, Orange=Orange, Banana=Yellow, Apple=Red}
Size of the HashMap: 4

containsKey() and containsValue() Methods

boolean containsKey(Object key): Returns true if this map contains a mapping for the specified key.

boolean containsValue(Object value): Returns true if this map maps one or more keys to the specified value

Here's an example demonstrating the usage of containsKey() and containsValue() methods in HashMap.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Creating a HashMap object
        HashMap<String, Integer> studentMarks = new HashMap<>();

        // Using put() method to add key-value pairs to the HashMap
        studentMarks.put("Alice", 85);
        studentMarks.put("Bob", 90);
        studentMarks.put("Charlie", 95);

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

        // Checking if the HashMap contains a specific key
        System.out.println("Does the HashMap contain key 'Alice'? " + studentMarks.containsKey("Alice"));
        System.out.println("Does the HashMap contain key 'Eve'? " + studentMarks.containsKey("Eve"));

        // Checking if the HashMap contains a specific value
        System.out.println("Does the HashMap contain value 90? " + studentMarks.containsValue(90));
        System.out.println("Does the HashMap contain value 100? " + studentMarks.containsValue(100));
    }
}

Output:

HashMap: {Bob=90, Alice=85, Charlie=95}
Does the HashMap contain key 'Alice'? true
Does the HashMap contain key 'Eve'? false
Does the HashMap contain value 90? true
Does the HashMap contain value 100? false

We used containsKey() and containsValue() methods to check whether the HashMap contains a specific key or value, respectively. The containsKey() method returns true if the specified key is present in the HashMap, and the containsValue() method returns true if the specified value is present in the HashMap. Otherwise, they return false.

void clear()

The clear() method is used to remove all of the mappings from HashMap.

Here's an example demonstrating the usage of a clear() method in a HashMap:
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Creating a HashMap object
        HashMap<String, Integer> studentMarks = new HashMap<>();

        // Using put() method to add key-value pairs to the HashMap
        studentMarks.put("Alice", 85);
        studentMarks.put("Bob", 90);
        studentMarks.put("Charlie", 95);

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

        // Using the clear() method to remove all key-value pairs from the HashMap
        studentMarks.clear();

        // Displaying the HashMap after calling clear()
        System.out.println("HashMap after calling clear(): " + studentMarks);
    }
}

Output:

Initial HashMap: {Bob=90, Alice=85, Charlie=95}
HashMap after calling clear(): {}

In this example, we used the clear() method to remove all key-value pairs from the HashMap, effectively emptying it. We display the HashMap again after calling clear(), and as you can see, it's now empty.

isEmpty() Method

The isEmpty() method returns true if this map contains no key-value mappings.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
      HashMap<Integer, String> map = new HashMap<>();
        System.out.println("Is map empty? " + map.isEmpty());
    }
}


Output:

Is map empty? true

values() Method

The values() method returns a Collection view of the values contained in HashMap.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Creating a HashMap object
        HashMap<String, Integer> studentMarks = new HashMap<>();

        // Using put() method to add key-value pairs to the HashMap
        studentMarks.put("Alice", 85);
        studentMarks.put("Bob", 90);
        studentMarks.put("Charlie", 95);

        Collection<Integer> values = studentMarks.values();
        System.out.println("Values: " + values);
    }
}

Output:

Values: [90, 85, 95]

Conclusion

In this article, we have seen all the important and commonly used HashMap methods with examples. You can learn more about HashMap here: Learn Everything About HashMap

Comments