Java LinkedHashMap Methods Tutorial with Examples

LinkedHashMap is a part of the Java Collections Framework and provides an implementation of the Map interface. It maintains a doubly-linked list running through all of its entries, ensuring that the order of the elements is maintained as they were inserted. This tutorial will cover all methods of LinkedHashMap with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.

Table of Contents

  1. Introduction
  2. Key Points
  3. LinkedHashMap Methods
    • put()
    • putAll()
    • get()
    • remove()
    • clear()
    • size()
    • isEmpty()
    • containsKey()
    • containsValue()
    • keySet()
    • values()
    • entrySet()
    • forEach()
    • replace()
    • compute()
    • computeIfAbsent()
    • computeIfPresent()
    • merge()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example with CRUD Operations
  8. Conclusion

1. Introduction

A LinkedHashMap in Java is a part of the Java Collections Framework and provides a way to manage key-value pairs while maintaining the order of insertion. It is found in the java.util package and is backed by a hash table and a linked list, ensuring that elements are stored in the order they were inserted.

2. Key Points

  • LinkedHashMap allows null values and the null key.
  • It maintains the order of elements based on insertion order.
  • It is not synchronized.
  • It provides constant-time performance for basic operations like put, get, and remove.
  • It can be configured to maintain access order rather than insertion order.

3. LinkedHashMap Methods

3.1. put()

The put() method is used to insert key-value pairs into the LinkedHashMap.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits);
    }
}

Output:

{Apple=50, Banana=30, Mango=20}

3.2. putAll()

The putAll() method adds all key-value pairs from another map to the LinkedHashMap.

Example:

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

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);

        Map<String, Integer> moreFruits = new LinkedHashMap<>();
        moreFruits.put("Mango", 20);
        moreFruits.put("Orange", 40);

        fruits.putAll(moreFruits);
        System.out.println(fruits);
    }
}

Output:

{Apple=50, Banana=30, Mango=20, Orange=40}

3.3. get()

The get() method retrieves the value associated with the specified key.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.get("Banana")); // 30
    }
}

Output:

30

3.4. remove()

The remove() method removes the key-value pair associated with the specified key.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.remove("Banana");
        System.out.println(fruits); // {Apple=50, Mango=20}
    }
}

Output:

{Apple=50, Mango=20}

3.5. clear()

The clear() method removes all key-value pairs from the LinkedHashMap.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.clear();
        System.out.println(fruits); // {}
    }
}

Output:

{}

3.6. size()

The size() method returns the number of key-value pairs in the LinkedHashMap.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.size()); // 3
    }
}

Output:

3

3.7. isEmpty()

The isEmpty() method checks if the LinkedHashMap is empty.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        System.out.println(fruits.isEmpty()); // true
        fruits.put("Apple", 50);
        System.out.println(fruits.isEmpty()); // false
    }
}

Output:

true
false

3.8. containsKey()

The containsKey() method checks if the LinkedHashMap contains a specified key.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        System.out.println(fruits.containsKey("Banana")); // true
        System.out.println(fruits.containsKey("Mango")); // false
    }
}

Output:

true
false

3.9. containsValue()

The containsValue() method checks if the LinkedHashMap contains a specified value.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        System.out.println(fruits.containsValue(30)); // true
        System.out.println(fruits.containsValue(20)); // false
    }
}

Output:

true
false

3.10. keySet()

The keySet() method returns a set view of the keys contained in the LinkedHashMap.

Example:

import java.util.LinkedHashMap;
import java.util.Set;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Set<String> keys = fruits.keySet();
        System.out.println(keys); // [Apple, Banana, Mango]
    }
}

Output:

[Apple, Banana, Mango]

3.11. values()

The values() method returns a collection view of the values contained in the LinkedHashMap.

Example:

import java.util.LinkedHashMap;
import java.util.Collection;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Collection<Integer> values = fruits.values();
        System.out.println(values); // [50, 30, 20]
    }
}

Output:

[50, 30, 20]

3.12. entrySet()

The entrySet() method returns a set view of the mappings contained in the LinkedHashMap.

Example:

import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Map.Entry;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put



("Mango", 20);
        Set<Entry<String, Integer>> entries = fruits.entrySet();
        for (Entry<String, Integer> entry : entries) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Output:

Apple = 50
Banana = 30
Mango = 20

3.13. forEach()

The forEach() method performs the given action for each entry in the LinkedHashMap.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.forEach((key, value) -> System.out.println(key + " = " + value));
    }
}

Output:

Apple = 50
Banana = 30
Mango = 20

3.14. replace()

The replace() method replaces the entry for the specified key only if it is currently mapped to some value.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.replace("Banana", 40);
        System.out.println(fruits); // {Apple=50, Banana=40, Mango=20}
    }
}

Output:

{Apple=50, Banana=40, Mango=20}

3.15. compute()

The compute() method computes a new mapping for the specified key and its current mapped value (or null if there is no current mapping).

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.compute("Banana", (key, value) -> (value == null) ? 40 : value + 10);
        System.out.println(fruits); // {Apple=50, Banana=40}
    }
}

Output:

{Apple=50, Banana=40}

3.16. computeIfAbsent()

The computeIfAbsent() method computes a mapping for the specified key if it is not already present.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.computeIfAbsent("Mango", key -> 20);
        System.out.println(fruits); // {Apple=50, Banana=30, Mango=20}
    }
}

Output:

{Apple=50, Banana=30, Mango=20}

3.17. computeIfPresent()

The computeIfPresent() method computes a new mapping for the specified key if it is currently present.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.computeIfPresent("Banana", (key, value) -> value + 10);
        System.out.println(fruits); // {Apple=50, Banana=40}
    }
}

Output:

{Apple=50, Banana=40}

3.18. merge()

The merge() method merges the specified value with the existing value associated with the specified key.

Example:

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.merge("Banana", 20, (oldValue, newValue) -> oldValue + newValue);
        System.out.println(fruits); // {Apple=50, Banana=50}
    }
}

Output:

{Apple=50, Banana=50}

4. Use Cases

  • Caching: Storing key-value pairs for quick retrieval while maintaining insertion order.
  • Database representation: Representing tables with rows as key-value pairs while maintaining order.
  • Configuration settings: Storing application settings as key-value pairs with a specific order.

5. Best Practices

  • Use appropriate initial capacity: If the size of the map is known in advance, setting an initial capacity can improve performance.
  • Avoid frequent resizing: Adding elements frequently can cause resizing. Consider setting an appropriate initial capacity.
  • Use immutable keys: Using mutable objects as keys can lead to unpredictable behavior.

6. Performance Considerations

  • Constant-time performance: LinkedHashMap provides constant-time performance for basic operations like put, get, and remove.
  • Memory usage: Each entry in a LinkedHashMap requires additional memory for storing hash codes and pointers.
  • Thread safety: LinkedHashMap is not synchronized. Use Collections.synchronizedMap() or ConcurrentHashMap if thread safety is needed.

7. Real-time Example with CRUD Operations

Managing an Employee Directory:

Employee.java:

public class Employee {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

Main.java:

import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<Integer, Employee> employeeDirectory = new LinkedHashMap<>();

        // Create
        employeeDirectory.put(1, new Employee("Aarav", 20));
        employeeDirectory.put(2, new Employee("Vivaan", 22));
        employeeDirectory.put(3, new Employee("Diya", 21));

        // Read
        for (LinkedHashMap.Entry<Integer, Employee> entry : employeeDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Employee: " + entry.getValue());
        }

        // Update
        employeeDirectory.put(2, new Employee("Vivaan", 23));
        System.out.println("After Update:");
        for (LinkedHashMap.Entry<Integer, Employee> entry : employeeDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Employee: " + entry.getValue());
        }

        // Delete
        employeeDirectory.remove(1);
        System.out.println("After Deletion:");
        for (LinkedHashMap.Entry<Integer, Employee> entry : employeeDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Employee: " + entry.getValue());
        }
    }
}

Output:

ID: 1, Employee: Employee{name='Aarav', age=20}
ID: 2, Employee: Employee{name='Vivaan', age=22}
ID: 3, Employee: Employee{name='Diya', age=21}
After Update:
ID: 2, Employee: Employee{name='Vivaan', age=23}
ID: 3, Employee: Employee{name='Diya', age=21}
After Deletion:
ID: 2, Employee: Employee{name='Vivaan', age=23}
ID: 3, Employee: Employee{name='Diya', age=21}

8. Conclusion

The LinkedHashMap class in Java is a powerful class for managing key-value pairs while maintaining insertion order. By understanding its methods, use cases, and best practices, you can effectively utilize LinkedHashMap in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.

Comments