How to Remove Key-Value Pairs or Entries from a HashMap in Java

This guide will cover the different approaches to removing entries or key-value pairs from the HashMap in Java.

Table of Contents

  1. Introduction
  2. Removing Entries by Key
  3. Removing Entries by Key and Value
  4. Removing Entries Using Iterator
  5. Removing Entries Using removeIf with Streams (Java 8 and above)
  6. Real-World Use Cases
  7. Conclusion

Introduction

A HashMap in Java stores key-value pairs and allows for fast retrieval, insertion, and deletion of entries. Sometimes, you may need to remove entries based on certain criteria, such as a specific key, a combination of key and value, or a condition applied to the entries. The following sections will demonstrate how to perform these operations.

Removing Entries by Key

You can remove an entry from a HashMap by specifying its key using the remove(Object key) method.

Example

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

public class RemoveByKeyExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Orange", 3);

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

        // Remove entry by key
        map.remove("Banana");

        System.out.println("Map after removing key 'Banana': " + map);
    }
}

Output:

Original map: {Apple=1, Banana=2, Orange=3}
Map after removing key 'Banana': {Apple=1, Orange=3}

Removing Entries by Key and Value

You can remove an entry from a HashMap by specifying both its key and value using the remove(Object key, Object value) method. This method removes the entry only if it is currently mapped to the specified value.

Example

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

public class RemoveByKeyValueExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Orange", 3);

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

        // Remove entry by key and value
        boolean removed = map.remove("Banana", 2);

        System.out.println("Was the entry removed? " + removed);
        System.out.println("Map after removing entry 'Banana'=2: " + map);
    }
}

Output:

Original map: {Apple=1, Banana=2, Orange=3}
Was the entry removed? true
Map after removing entry 'Banana'=2: {Apple=1, Orange=3}

Removing Entries Using Iterator

You can remove entries from a HashMap while iterating over it using an Iterator. This approach is useful when you need to remove entries based on a condition.

Example

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

public class RemoveUsingIteratorExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Orange", 3);
        map.put("Grapes", 2);

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

        // Remove entries with value 2 using iterator
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            if (entry.getValue().equals(2)) {
                iterator.remove();
            }
        }

        System.out.println("Map after removing entries with value 2: " + map);
    }
}

Output:

Original map: {Apple=1, Banana=2, Orange=3, Grapes=2}
Map after removing entries with value 2: {Apple=1, Orange=3}

Removing Entries Using removeIf with Streams (Java 8 and above)

Java 8 introduced the Stream API, which allows for a functional approach to remove entries based on a condition using the removeIf method.

Example

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

public class RemoveUsingStreamExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Orange", 3);
        map.put("Grapes", 2);

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

        // Remove entries with value 2 using streams
        map.entrySet().removeIf(entry -> entry.getValue().equals(2));

        System.out.println("Map after removing entries with value 2: " + map);
    }
}

Output:

Original map: {Apple=1, Banana=2, Orange=3, Grapes=2}
Map after removing entries with value 2: {Apple=1, Orange=3}

Real-World Use Cases

Removing Expired Sessions

In a web application, you might store user sessions in a HashMap with the session ID as the key and the session object as the value. You can remove expired sessions by iterating through the map and checking the expiration time.

Example

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

class Session {
    String id;
    long expirationTime;

    Session(String id, long expirationTime) {
        this.id = id;
        this.expirationTime = expirationTime;
    }

    boolean isExpired() {
        return System.currentTimeMillis() > expirationTime;
    }
}

public class SessionManager {
    public static void main(String[] args) {
        Map<String, Session> sessions = new HashMap<>();
        sessions.put("session1", new Session("session1", System.currentTimeMillis() + 10000)); // expires in 10 seconds
        sessions.put("session2", new Session("session2", System.currentTimeMillis() - 10000)); // expired

        System.out.println("Original sessions: " + sessions);

        // Remove expired sessions
        Iterator<Map.Entry<String, Session>> iterator = sessions.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Session> entry = iterator.next();
            if (entry.getValue().isExpired()) {
                iterator.remove();
            }
        }

        System.out.println("Sessions after removing expired: " + sessions);
    }
}

Output:

Original sessions: {session1=Session@1b6d3586, session2=Session@4554617c}
Sessions after removing expired: {session1=Session@1b6d3586}

Conclusion

Removing key-value pairs from a HashMap in Java can be done in several ways, including by key, by key and value, using an iterator, or using the removeIf method with streams. Each method has its own use cases and can be chosen based on the specific requirements of your application. Understanding these methods helps you manage HashMap entries efficiently in your Java programs.

Comments