1. Introduction

A LinkedHashMap is a hash table and linked list implementation of the Map interface, with predictable iteration order. It maintains a doubly-linked list running through all its entries, which allows it to provide order-of-insertion or order-of-access. Removing entries from a LinkedHashMap is as straightforward as using its remove method, and in this blog post, we’ll walk you through the steps to do so.

2. Program Steps

1. Create and populate a LinkedHashMap.

2. Print the original LinkedHashMap.

3. Remove an entry based on a specific key.

4. Remove entries conditionally using the removeIf method.

5. Display the updated LinkedHashMap.

3. Code Program

import java.util.LinkedHashMap;

public class RemoveFromLinkedHashMap {

    public static void main(String[] args) {

        // Step 1: Create and populate a LinkedHashMap
        LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
        scores.put("Alice", 90);
        scores.put("Bob", 85);
        scores.put("Charlie", 78);
        scores.put("Dave", 93);

        // Displaying the original LinkedHashMap
        System.out.println("Original LinkedHashMap: " + scores);

        // Step 2: Remove an entry based on a specific key
        scores.remove("Alice");

        // Step 3: Remove entries conditionally using the removeIf method
        scores.removeIf((key, value) -> value < 90);  // Remove entries with scores less than 90

        // Step 4: Display the updated LinkedHashMap
        System.out.println("Updated LinkedHashMap: " + scores);
    }
}

Output:

Original LinkedHashMap: {Alice=90, Bob=85, Charlie=78, Dave=93}
Updated LinkedHashMap: {Dave=93}

4. Step By Step Explanation

Step 1: We create a LinkedHashMap named scores and populate it with student names as keys and their scores as values.

Step 2: We use the remove method to remove the entry with the key "Alice". The remove method removes the mapping for the specified key if present and returns the value to which the specified key was previously mapped, or null if the map contained no mapping for the key.

Step 3: The removeIf method is a newer addition to the Map interface, which provides a way to remove entries based on a condition. In our example, we're removing entries where the score (value) is less than 90.

Step 4: We display the LinkedHashMap after the removal operations to see the updated entries.

From the output, it's evident that only the entry for Dave remains in the LinkedHashMap post the removal operations, since Dave's score is the only one greater than or equal to 90.