Java LinkedHashMap

The HashMap class doesn’t guarantee any specific iteration order of the elements. It doesn’t keep track of the order in which the elements are inserted and produces the elements in a random order every time you iterate over it. If you want a predictable iteration order of the elements in a Map, then you can use a LinkedHashMap.

Important Key Points about Java LinkedHashMap

Below are some important points about Java LinkedHashMap: 

Order of elements: 

Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable.

Null Keys and Values: 

Similar to HashMap, LinkedHashMap allows one null key and multiple null values. 

Not Synchronized: 

LinkedHashMap is not synchronized, which means it's not thread-safe. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. 

Performance: 

The performance of LinkedHashMap can be slightly lower than HashMap due to the overhead of maintaining the linked list. But the difference is usually negligible unless you're dealing with very large numbers of entries. 

Usage: 

LinkedHashMap is useful in situations where you need a Map that also maintains its elements in order. This is particularly useful when you want to iterate over the keys or values of the map in a specific order that matches the order you added the elements.

Create LinkedHashMap

Here is the syntax to create an object of LinkedHashMap class:
// Creating a LinkedHashMap
LinkedHashMap<String, Integer> dayNumberMapping = new LinkedHashMap<>();

Add Elements to LinkedHashMap

The put() method is used to add elements to the LinkedHashMap.
// Creating a LinkedHashMap
LinkedHashMap<String, Integer> dayNumberMapping = new LinkedHashMap<>();

// Adding new key-value pairs to the LinkedHashMap
dayNumberMapping.put("Mon", 1);
dayNumberMapping.put("Tus", 2);
dayNumberMapping.put("Wen", 3);
dayNumberMapping.put("Thu", 4);
dayNumberMapping.put("Fri", 5);
dayNumberMapping.put("Sat", 6);

System.out.println(dayNumberMapping);
Output:
{Mon=1, Tus=2, Wen=3, Thu=4, Fri=5, Sat=6, Sun=7}

Access Elements from LinkedHashMap

We can access elements from a LinkedHashMap using the get() method. 

Here's an example with output:
import java.util.LinkedHashMap;
import java.util.Map;

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

        // Add elements to the LinkedHashMap
        students.put("John", 12);
        students.put("Alice", 15);
        students.put("Bob", 14);

        // Access elements from the LinkedHashMap
        int johnAge = students.get("John");
        int aliceAge = students.get("Alice");
        int bobAge = students.get("Bob");

        System.out.println("John's Age: " + johnAge);
        System.out.println("Alice's Age: " + aliceAge);
        System.out.println("Bob's Age: " + bobAge);
    }
}

Output:

John's Age: 12
Alice's Age: 15
Bob's Age: 14
In this example, we're using the get() method with the key of the element we want to access as the argument. This will return the value associated with that key.

Remember, if the key is not present in the map, the get() method will return null.

Remove Elements from LinkedHashMap

Removing entries from a LinkedHashMap can be done using the remove() method, which takes the key of the element to be removed as a parameter. Here is an example:
import java.util.LinkedHashMap;
import java.util.Map;

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

        // Add elements to the LinkedHashMap
        students.put("John", 12);
        students.put("Alice", 15);
        students.put("Bob", 14);

        System.out.println("Initial LinkedHashMap: " + students);

        // Remove the entry with key 'Alice'
        students.remove("Alice");

        System.out.println("LinkedHashMap after removing Alice: " + students);
    }
}

Output:

Initial LinkedHashMap: {John=12, Alice=15, Bob=14}
LinkedHashMap after removing Alice: {John=12, Bob=14}
As you can see, the entry with the key "Alice" is no longer present in the LinkedHashMap after the remove() operation. If the key is not found in the LinkedHashMap, the remove() method simply does nothing and returns null.

Search Elements in LinkedHashMap

Searching for elements in a LinkedHashMap can be performed using the containsKey() and containsValue() methods. 

The containsKey() method is used to check if a specific key is present in the map, while the containsValue() method is used to check if a specific value is present in the map. 

Here's an a complete example with output:
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        
        // Add some elements to the LinkedHashMap
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);
        
        // Search for a key in the LinkedHashMap
        boolean exists = map.containsKey("Two");
        System.out.println("Does key 'Two' exist? " + exists);
        
        // Search for a value in the LinkedHashMap
        exists = map.containsValue(3);
        System.out.println("Does value '3' exist? " + exists);
    }
}

Output:

Does key 'Two' exist? true
Does value '3' exist? true

Iterate or Loop over a LinkedHashMap

Iterate over a LinkedHashMap using Java 8 forEach and lambda expression:

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

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

        // Using Java 8 forEach and lambda expression
        map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output:

Key: One, Value: 1
Key: Two, Value: 2
Key: Three, Value: 3

Iterate over a LinkedHashMap’s entrySet using Java 8 forEach and lambda expression:

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

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

        // Using Java 8 forEach and lambda expression over entrySet
        map.entrySet().forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()));
    }
}

Output:

Key: One, Value: 1
Key: Two, Value: 2
Key: Three, Value: 3

Iterate over a LinkedHashMap’s entrySet using iterator():

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

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

        // Using iterator over entrySet
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Output:

Key: One, Value: 1
Key: Two, Value: 2
Key: Three, Value: 3
Iterate over a LinkedHashMap’s entrySet using iterator() and Java 8 forEachRemaining() method:
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

        // Using iterator and Java 8 forEachRemaining() method over entrySet
        map.entrySet().iterator().forEachRemaining(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()));
    }
}

Output:

Key: One, Value: 1
Key: Two, Value: 2
Key: Three, Value: 3

LinkedHashMap with User-Defined Objects

Here is an example of using a LinkedHashMap with user-defined objects. In this case, let's define a simple Person class and use it in a LinkedHashMap.

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

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<Integer, Person> map = new LinkedHashMap<>();
        
        // Adding elements to the map
        map.put(1, new Person("Alice", 25));
        map.put(2, new Person("Bob", 30));
        map.put(3, new Person("Charlie", 35));

        // Iterating over the map
        for(Map.Entry<Integer, Person> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Output:

Key: 1, Value: Person{name='Alice', age=25}
Key: 2, Value: Person{name='Bob', age=30}
Key: 3, Value: Person{name='Charlie', age=35}

Conclusion 

In this article, you learned what is a LinkedHashMap, how to create a LinkedHashMap, how to add new key-value pairs to a LinkedHashMap, how to remove entries from a LinkedHashMap, how to search elements in LinkedHashMap, how to iterate over a LinkedHashMap, and how to use LinkedHashMap with user-defined objects.

Comments