Skip to content

Java LinkedHashMap

LinkedHashMap—a magical data structure that combines the best of both worlds: the ordered nature of a linked list and the key-value mapping of a hash table. Join me as we delve into the depths of LinkedHashMap, blending technical insights with a personal touch.

Imagine you're exploring a mystical forest where every tree holds a secret treasure. Each treasure is marked with a unique key, guiding you to its hidden location. That's precisely what LinkedHashMap does—it maps keys to values, allowing you to retrieve treasures swiftly while maintaining the order in which they were added.

But what sets LinkedHashMap apart from other map implementations? Well, picture it as a storyteller weaving a tale—the linked list maintains the insertion order of elements, while the hash table ensures quick access to each treasure by its key. It's like having a magical map that not only leads you to the treasures but also chronicles your journey along the way.

Now, let's take a closer look at how LinkedHashMap works:

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

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap to store the treasures and their descriptions
        Map<String, String> treasureMap = new LinkedHashMap<>();

        // Add treasures to the map
        treasureMap.put("Golden Key", "Unlocks hidden chambers");
        treasureMap.put("Crystal Amulet", "Grants protection from dark forces");
        treasureMap.put("Enchanted Scroll", "Reveals ancient secrets");

        // Display the treasures and their descriptions
        for (Map.Entry<String, String> entry : treasureMap.entrySet()) {
            System.out.println("Treasure: " + entry.getKey() + ", Description: " + entry.getValue());
        }
    }
}

In our example, we've created a LinkedHashMap to store treasures and their descriptions. As we add treasures to the map, LinkedHashMap ensures that they are stored in the order they were added. When we iterate over the map, the treasures are displayed in the same order, preserving their insertion sequence.

But wait, there's more to LinkedHashMap than meets the eye! It offers additional features like access-ordering, which reorders elements based on their access patterns, making it perfect for building cache-like structures or implementing LRU (Least Recently Used) caches.

Features of the LinkedHashMap class.

  1. Preserving Insertion Order: Unlike the regular HashMap, which doesn't guarantee any specific order of its elements, a LinkedHashMap maintains the order in which key-value pairs were inserted. This makes it ideal for scenarios where you need to iterate over the map in the same order as the entries were added.

  2. Access Order Mode: In addition to insertion order, LinkedHashMap also supports an access order mode, where the most recently accessed elements are moved to the end of the iteration order. This can be useful for implementing least recently used (LRU) cache-like structures.

  3. Performance: Despite its ordered nature, LinkedHashMap provides constant-time performance for basic operations such as get, put, and remove, just like a regular HashMap. This makes it efficient for use in a wide range of applications.

Practical example to see the LinkedHashMap

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

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap with a capacity of 3 and access order mode
        LinkedHashMap<String, Integer> scores = new LinkedHashMap<>(3, 0.75f, true);

        // Insert some key-value pairs
        scores.put("Alice", 95);
        scores.put("Bob", 80);
        scores.put("Charlie", 75);

        // Access Bob to make it the most recently accessed entry
        scores.get("Bob");

        // Iterate over the map to observe the order
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

In this example, we create a LinkedHashMap with a capacity of 3 and access order mode enabled. We then insert some key-value pairs and access one of them (Bob) to demonstrate access order mode. Finally, we iterate over the map to observe the preserved insertion order.

Isn't that fascinating? With LinkedHashMap, you get the flexibility of a map combined with the predictability of ordered traversal. Whether you're building a cache, maintaining a history of user actions, or simply need to preserve insertion order, LinkedHashMap has got you covered.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.