1. Introduction

The LinkedHashMap in Java inherits from the HashMap class and additionally maintains a doubly-linked list to preserve the insertion order of its entries. While LinkedHashMap does not have direct methods to remove the first and last elements, we can achieve this by accessing its keys. In this post, we’ll explore how to remove the first and last elements from a LinkedHashMap.

2. Program Steps

1. Create a LinkedHashMap and add some elements.

2. Identify and remove the first entry.

3. Identify and remove the last entry.

4. Display the remaining elements of the LinkedHashMap.

3. Code Program

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapRemoveFirstLast {

    public static void main(String[] args) {

        // Step 1: Create a LinkedHashMap and add some elements
        LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
        capitals.put("USA", "Washington DC");
        capitals.put("UK", "London");
        capitals.put("India", "New Delhi");
        capitals.put("Canada", "Ottawa");

        // Step 2: Identify and remove the first entry
        String firstKey = capitals.keySet().iterator().next();
        capitals.remove(firstKey);

        // Step 3: Identify and remove the last entry
        String lastKey = new ArrayList<>(capitals.keySet()).get(capitals.size() - 1);
        capitals.remove(lastKey);

        // Step 4: Display the remaining elements of the LinkedHashMap
        System.out.println("Remaining elements in the LinkedHashMap:");
        for (Map.Entry<String, String> entry : capitals.entrySet()) {
            System.out.println(entry.getKey() + " - " + entry.getValue());
        }
    }
}

Output:

Remaining elements in the LinkedHashMap:
UK - London

4. Step By Step Explanation

Step 1: We initialize a LinkedHashMap named capitals with country names as keys and their capitals as values.

Step 2: To remove the first element, we first fetch the key of the first entry using the iterator().next() method on the keySet of the LinkedHashMap. Then, we call the remove method with this key.

Step 3: Removing the last element is a bit trickier since there's no direct way to get the last key. As a workaround, we convert the key set of the LinkedHashMap to an ArrayList and fetch the last element. We then use this key with the remove method.

Step 4: We display the remaining elements in the LinkedHashMap by iterating over its entries. As seen in the output, only the middle element "UK – London" remains after removing the first and last elements.