Java HashMap

Java HashMap


Java HashMap implements Map interface and is used for storing items in key/value pairs, and you access a value by its key, and HashMap keys must be unique.
HashMap can have null value and null key.

Add elements to a HashMap
We use put() method to add key-value pairs to a HashMap.


import java.util.HashMap;

public class HashMapAddKeyValue {
    public static void main(String[] args) {
        HashMap<String, Integer> shoppingCart = new HashMap<>();
        shoppingCart.put("Coffee", 1);
        shoppingCart.put("Milk", 2);
        shoppingCart.put("Bread", 4);
        shoppingCart.put("Butter", 1);
        shoppingCart.put("Cheese", 3);
        shoppingCart.put(null, null);

        System.out.println("My Shopping Cart:" + shoppingCart);

    }
}


Output:


$ javac HashMapAddKeyValue.java
$ java HashMapAddKeyValue
My Shopping Cart:{null=null, Butter=1, Cheese=3, Coffee=1, Milk=2, Bread=4}


We use the remove() method do remove a key from HashMap


import java.util.HashMap;

public class HashMapRemove {
    public static void main(String[] args) {
        HashMap<String, Integer> shoppingCart = new HashMap<>();
        shoppingCart.put("Coffee", 1);
        shoppingCart.put("Milk", 2);
        shoppingCart.put("Bread", 4);
        shoppingCart.put("Butter", 1);
        shoppingCart.put("Cheese", 3);
        shoppingCart.put("Candy", 1000);

        System.out.println("My Shopping Cart:" + shoppingCart);

        shoppingCart.remove("Candy");

        System.out.println("My Shopping Cart: " + shoppingCart);
    }
}


Output:


$ javac HashMapRemove.java
$ java HashMapRemove
My Shopping Cart:{Butter=1, Candy=1000, Cheese=3, Coffee=1, Milk=2, Bread=4}
My Shopping Cart: {Butter=1, Cheese=3, Coffee=1, Milk=2, Bread=4}


Iterating over a HashMap
The following example shows how to iterate over a HashMap.


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

public class IterateHashMap {
    public static void main(String[] args) {
        HashMap<String, Integer> shoppingCart = new HashMap<>();
        shoppingCart.put("Coffee", 1);
        shoppingCart.put("Milk", 2);
        shoppingCart.put("Bread", 4);
        shoppingCart.put("Butter", 1);
        shoppingCart.put("Cheese", 3);

        // Iterate using forEach and lambda expression
        shoppingCart.forEach((item, quantity) -> {
            System.out.println("Buy " + quantity + " " + item);
        });

        System.out.println("===================");

        // Iterate HashMap entrySet using iterator() method
        Set<Map.Entry<String, Integer>> shoppingCartEntries = shoppingCart.entrySet();
        Iterator<Map.Entry<String, Integer>> shoppingCartItr = shoppingCartEntries.iterator();
        while (shoppingCartItr.hasNext()) {
            Map.Entry<String, Integer> entry = shoppingCartItr.next();
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        System.out.println("===================");

        // Iterate HashMap entrySet using for-each loop
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            System.out.println("Buy " + entry.getValue() + " " + entry.getKey());
        }
    }
}


Output:


$ javac IterateHashMap.java
$ java IterateHashMap
Buy 1 Butter
Buy 3 Cheese
Buy 1 Coffee
Buy 2 Milk
Buy 4 Bread
===================
Butter : 1
Cheese : 3
Coffee : 1
Milk : 2
Bread : 4
===================
Buy 1 Butter
Buy 3 Cheese
Buy 1 Coffee
Buy 2 Milk
Buy 4 Bread


The following example shows how to create a map using custom objects.


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

class Cart {
    private String item;
    private Integer quantity;

    public Cart(String item, Integer quantity) {
        this.item = item;
        this.quantity = quantity;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return String.format(
            "Cart{item='%s', quantity=%d}",
            item, quantity);
    }
}

public class CustomHashMapObject {
    public static void main(String[] args) {
        Map<Integer, Cart> cart = new HashMap<>();
        cart.put(1, new Cart("Coffee", 1));
        cart.put(2, new Cart("Milk", 2));
        cart.put(3, new Cart("Bread", 1));
        cart.put(4, new Cart("Butter", 1));
        cart.put(5, new Cart("Cheese", 4));
        cart.put(6, new Cart("Candy", 1000));

        System.out.println(cart);
        
        // we use containsKey() method to check if the key is present in the map
        System.out.println("Map contains key 6: " + cart.containsKey(6));

        // we use remove() method to remove the object from the map with the specified key
        cart.remove(6);
        System.out.println("Remove object with key 6");

        System.out.println("Map contains key 6: " + cart.containsKey(6));
    }
}


Output:


$ javac CustomHashMapObject.java
$ java CustomHashMapObject
{1=Cart{item='Coffee', quantity=1}, 2=Cart{item='Milk', quantity=2}, 3=Cart{item='Bread', quantity=1}, 4=Cart{item='Butter', quantity=1}, 5=Cart{item='Cheese', quantity=4}, 6=Cart{item='Candy', quantity=1000}}
Map contains key 6: true
Remove object with key 6
Map contains key 6: false


Share this: