Java HashMap

Java Setinterface

What is Java HashMap?

Java HashMap is a collection class that implements the Map interface to store key-value pairs. It uses hash tables for efficient key lookup and offers constant-time performance for basic operations such as add, remove, and get.

It permits null values and keys and allows for the insertion of duplicate keys but not duplicate values. HashMap is not thread-safe, but it can be synchronized using the Collections.synchronizedMap() method.

To understand the more about Java HashMap, Read the Complete Article.

How to create a Java HashMap

  • Import the java.util.HashMap class
  • Create a new instance of the HashMap class
  • Add key-value pairs to the HashMap using the put() method
  • Retrieve the value associated with a key using the get() method
  • Remove a key-value pair from the HashMap using the remove() method
  • Check if a key is present in the HashMap using the containsKey() method
Java HashMap hierarcy

Advantages Of Java HashMap: 

Java HashMap

Methods of Java HashMap: 

MethodsDescription
put(key, value)Adds a new key-value pair to the HashMap, or replaces the value if the key already exists.
get(key)Returns the value associated with the specified key, or null if the key is not present in the HashMap.
containsKey(key)Returns true if the HashMap contains the specified key, false otherwise.
size():Returns the number of key-value pairs in the HashMap..
clear():Removes all key-value pairs from the HashMap.
isEmpty(): Returns true if the HashMap contains no key-value pairs, false otherwise.
remove(key): Removes the key-value pair associated with the specified key from the HashMap, if it exists.
values():Returns a Collection containing all the values in the HashMap.

These are some methods that can be used to manipulate and access the elements in a HashMap.

Iterate through a HashMap

  • Using the keySet() method: The keySet() method returns a Set view of the keys stored in the HashMap. You can iterate over this set of keys and retrieve the corresponding values from the HashMap using the get() method.
  • Using the entrySet() method: The entrySet() method returns a Set view of the key-value pairs stored in the HashMap as Map.Entry objects. You can iterate over this set of entries and retrieve the key and value from each entry.
  • Using Java 8 streams: If you are using Java 8 or later, you can use streams to iterate over the key-value pairs in a HashMap.

Example 1: Java Program to create a HashMap

Run
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Create a new HashMap
        HashMap<String, Integer> myMap = new HashMap<>();
        
        // Add key-value pairs to the HashMap
        myMap.put("apple", 1);
        myMap.put("banana", 2);
        myMap.put("orange", 3);
        
        // Retrieve the value associated with a key
        int value = myMap.get("banana");
        System.out.println(value); // Output: 2
        
        // Remove a key-value pair from the HashMap
        myMap.remove("orange");
        
        // Check if a key is present in the HashMap
        boolean hasKey = myMap.containsKey("apple");
        System.out.println(hasKey); // Output: true
        
        // Iterate over the keys and values in the HashMap
        for (String key : myMap.keySet()) {
            int val = myMap.get(key);
            System.out.println(key + " -> " + val);
        }
        
        // Clear all the key-value pairs from the HashMap
        myMap.clear();
    }
}

Output

2
true
banana -> 2
apple -> 1

Example 2: Basic Operations on Java HashMap

Run
import java.util.HashMap;

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

        // add elements to the HashMap
        myMap.put("apple", 1);
        myMap.put("banana", 2);
        myMap.put("orange", 3);
        System.out.println("HashMap after adding elements: " + myMap);

        // access elements from the HashMap
        int appleValue = myMap.get("apple");
        System.out.println("Value of 'apple': " + appleValue);

        // change elements in the HashMap
        myMap.put("banana", 4);
        System.out.println("HashMap after changing 'banana': " + myMap);

        // remove elements from the HashMap
        myMap.remove("orange");
        System.out.println("HashMap after removing 'orange': " + myMap);
    }
}

Output

HashMap after adding elements: {banana=2, orange=3, apple=1}
Value of 'apple': 1
HashMap after changing 'banana': {banana=4, orange=3, apple=1}
HashMap after removing 'orange': {banana=4, apple=1}

Example 3: Basic Operations on Java HashMap

Run
import java.util.HashMap;

import java.util.Map;

//HashMapFromOtherMaps
public class Main
{

  public static void main (String[]args)
  {

    // create a HashMap from an existing Map object
    Map < String, Integer > map1 = new HashMap <> ();

    map1.put ("apple", 1);

    map1.put ("banana", 2);

    map1.put ("orange", 3);


    Map < String, Integer > map2 = new HashMap <> ();

    map2.put ("grapes", 4);

    map2.put ("kiwi", 5);


    Map < String, Integer > newMap = new HashMap <> ();

    newMap.putAll (map1);

    newMap.putAll (map2);


    System.out.println ("New HashMap: " + newMap);

  }
}

Output

New HashMap: {banana=2, orange=3, apple=1, kiwi=5, grapes=4}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription