Java LinkedHashMap Example

In this tutorial, we will explore the LinkedHashMap class in Java, which is a specialized implementation of the Map interface. Unlike the standard HashMap, LinkedHashMap maintains the insertion order of its entries. This tutorial will demonstrate how to use LinkedHashMap with examples, including all important operations and different ways to iterate using Java 8 features.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Step-by-Step Guide
    1. Creating a LinkedHashMap
    2. Adding and Retrieving Elements
    3. Iterating Over the Map
    4. Removing Elements
    5. Access Order LinkedHashMap
  4. Complete Code Example
  5. Conclusion

Introduction

LinkedHashMap is a part of Java's java.util package and extends HashMap. It maintains a doubly-linked list running through all its entries, ensuring the order of the keys is preserved either by insertion order or access order. This makes LinkedHashMap useful in scenarios where the order of elements is important.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed (latest version preferred)
  • An Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse

Step-by-Step Guide

Step 1: Creating a LinkedHashMap

First, let's create a LinkedHashMap and add some key-value pairs to it.

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

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Print the map
        System.out.println("LinkedHashMap: " + linkedMap);
    }
}

Output:

LinkedHashMap: {Ravi=25, Sita=30, Arjun=22, Lakshmi=20}

Step 2: Adding and Retrieving Elements

Let's add some elements to the LinkedHashMap and retrieve values using different keys.

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Retrieve and print values using different keys
        System.out.println("Ravi: " + linkedMap.get("Ravi"));
        System.out.println("Sita: " + linkedMap.get("Sita"));
    }
}

Output:

Ravi: 25
Sita: 30

Step 3: Iterating Over the Map

We can iterate over the LinkedHashMap using the entry set, key set, or values. We will also use Java 8 features like forEach and streams.

Using Entry Set

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Iterate over the map using entry set
        System.out.println("Iterating over LinkedHashMap using entry set:");
        for (Map.Entry<String, Integer> entry : linkedMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

Iterating over LinkedHashMap using entry set:
Ravi: 25
Sita: 30
Arjun: 22
Lakshmi: 20

Using Key Set

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Iterate over the map using key set
        System.out.println("Iterating over LinkedHashMap using key set:");
        for (String key : linkedMap.keySet()) {
            System.out.println(key + ": " + linkedMap.get(key));
        }
    }
}

Output:

Iterating over LinkedHashMap using key set:
Ravi: 25
Sita: 30
Arjun: 22
Lakshmi: 20

Using Values

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Iterate over the map using values
        System.out.println("Iterating over LinkedHashMap using values:");
        for (Integer value : linkedMap.values()) {
            System.out.println(value);
        }
    }
}

Output:

Iterating over LinkedHashMap using values:
25
30
22
20

Using forEach and Lambda Expression (Java 8)

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Iterate over the map using forEach and lambda
        System.out.println("Iterating over LinkedHashMap using forEach and lambda:");
        linkedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Output:

Iterating over LinkedHashMap using forEach and lambda:
Ravi: 25
Sita: 30
Arjun: 22
Lakshmi: 20

Step 4: Removing Elements

Let's remove elements from the LinkedHashMap and demonstrate the use of remove method.

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Remove an element
        linkedMap.remove("Arjun");

        // Print the map after removal
        System.out.println("LinkedHashMap after removal: " + linkedMap);
    }
}

Output:

LinkedHashMap after removal: {Ravi=25, Sita=30, Lakshmi=20}

Step 5: Access Order LinkedHashMap

LinkedHashMap can be configured to order its entries based on access order rather than insertion order. This is useful for implementing LRU (Least Recently Used) caches.

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create an access-order LinkedHashMap
        LinkedHashMap<String, Integer> accessOrderMap = new LinkedHashMap<>(16, 0.75f, true);

        // Add key-value pairs to the map
        accessOrderMap.put("Ravi", 25);
        accessOrderMap.put("Sita", 30);
        accessOrderMap.put("Arjun", 22);
        accessOrderMap.put("Lakshmi", 20);

        // Access some elements
        accessOrderMap.get("Arjun");
        accessOrderMap.get("Ravi");

        // Print the map after access
        System.out.println("Access order LinkedHashMap: " + accessOrderMap);
    }
}

Output:

Access order LinkedHashMap: {Sita=30, Lakshmi=20, Arjun=22, Ravi=25}

Complete Code Example

Here's the complete code example demonstrating various operations with LinkedHashMap:

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

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        Map<String, Integer> linkedMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        linkedMap.put("

Ravi", 25);
        linkedMap.put("Sita", 30);
        linkedMap.put("Arjun", 22);
        linkedMap.put("Lakshmi", 20);

        // Retrieve and print values using different keys
        System.out.println("Ravi: " + linkedMap.get("Ravi"));
        System.out.println("Sita: " + linkedMap.get("Sita"));

        // Iterate over the map using entry set
        System.out.println("Iterating over LinkedHashMap using entry set:");
        for (Map.Entry<String, Integer> entry : linkedMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Iterate over the map using key set
        System.out.println("Iterating over LinkedHashMap using key set:");
        for (String key : linkedMap.keySet()) {
            System.out.println(key + ": " + linkedMap.get(key));
        }

        // Iterate over the map using values
        System.out.println("Iterating over LinkedHashMap using values:");
        for (Integer value : linkedMap.values()) {
            System.out.println(value);
        }

        // Iterate over the map using forEach and lambda
        System.out.println("Iterating over LinkedHashMap using forEach and lambda:");
        linkedMap.forEach((key, value) -> System.out.println(key + ": " + value));

        // Remove an element
        linkedMap.remove("Arjun");
        System.out.println("LinkedHashMap after removal: " + linkedMap);

        // Create an access-order LinkedHashMap
        LinkedHashMap<String, Integer> accessOrderMap = new LinkedHashMap<>(16, 0.75f, true);

        // Add key-value pairs to the map
        accessOrderMap.put("Ravi", 25);
        accessOrderMap.put("Sita", 30);
        accessOrderMap.put("Arjun", 22);
        accessOrderMap.put("Lakshmi", 20);

        // Access some elements
        accessOrderMap.get("Arjun");
        accessOrderMap.get("Ravi");

        // Print the map after access
        System.out.println("Access order LinkedHashMap: " + accessOrderMap);
    }
}

Output:

Ravi: 25
Sita: 30
Iterating over LinkedHashMap using entry set:
Ravi: 25
Sita: 30
Arjun: 22
Lakshmi: 20
Iterating over LinkedHashMap using key set:
Ravi: 25
Sita: 30
Arjun: 22
Lakshmi: 20
Iterating over LinkedHashMap using values:
25
30
22
20
Iterating over LinkedHashMap using forEach and lambda:
Ravi: 25
Sita: 30
Arjun: 22
Lakshmi: 20
LinkedHashMap after removal: {Ravi=25, Sita=30, Lakshmi=20}
Access order LinkedHashMap: {Sita=30, Lakshmi=20, Arjun=22, Ravi=25}

Conclusion

In this tutorial, we demonstrated how to use the LinkedHashMap class in Java. We covered creating a LinkedHashMap, adding and retrieving elements, iterating over the map using various methods, removing elements, and using access order in LinkedHashMap. By following this guide, developers can effectively use LinkedHashMap in scenarios where the order of elements is important.

Comments