Java LinkedHashMap
A **LinkedHashMap** is a class in the **Java Collections Framework** that stores data as **key-value pairs** while preserving the **order in which the entries were inserted**.
The `LinkedHashMap` class belongs to the `java.util` package and implements the `Map` interface. It combines the fast lookup performance of a `HashMap` with predictable iteration order.
Unlike a `HashMap`, which does not guarantee any ordering, a `LinkedHashMap` always returns entries in the same order they were added.
## Why Use LinkedHashMap?
Choose a `LinkedHashMap` when you need to:
- Store data as key-value pairs.
- Preserve the insertion order of entries.
- Perform fast lookup, insertion, and deletion.
- Display data in the same order it was added.
- Maintain predictable iteration without sorting.
> **Tip:** If maintaining insertion order is important, use a `LinkedHashMap`. If ordering does not matter, a `HashMap` may offer slightly better performance.
---
# Creating a LinkedHashMap
To use a `LinkedHashMap`, import the `java.util.LinkedHashMap` class and create an object by specifying the data types for its keys and values.
Example
The following program creates a `LinkedHashMap` that stores product IDs and product names.
java id="lhm001"
import java.util.LinkedHashMap;
public class ProductMapExample {
public static void main(String[] args) {
LinkedHashMap<Integer, String> products = new LinkedHashMap<>()
products.put(101, "Laptop");
products.put(102, "Keyboard");
products.put(103, "Mouse");
System.out.println(products);
}
}
Output
text id="lhmout001"
{101=Laptop, 102=Keyboard, 103=Mouse}
The entries appear in the same order they were inserted.
Adding Items
Use the put() method to insert new key-value pairs into a LinkedHashMap.
If the specified key already exists, its value is updated while its original position in the insertion order remains unchanged.
Example
java id="lhm002"
import java.util.LinkedHashMap;
public class StudentExample {
public static void main(String[] args) {
LinkedHashMap<Integer, String> students = new LinkedHashMap<>();
students.put(201, "Emma");
students.put(202, "Oliver");
students.put(203, "Sophia");
// Update an existing key
students.put(202, "Olivia");
System.out.println(students);
}
}
Output
text id="lhmout002"
{201=Emma, 202=Olivia, 203=Sophia}
Note: A LinkedHashMap does not allow duplicate keys. If the same key is added again, the existing value is replaced.
Accessing an Item
Use the get() method to retrieve the value associated with a specific key.
Example
java id="lhm003"
import java.util.LinkedHashMap;
public class AccessExample {
public static void main(String[] args) {
LinkedHashMap<String, String> browsers = new LinkedHashMap<>();
browsers.put("GC", "Google Chrome");
browsers.put("FF", "Mozilla Firefox");
browsers.put("ED", "Microsoft Edge");
System.out.println(browsers.get("FF"));
}
}
Output
text id="lhmout003"
Mozilla Firefox
Removing Items
Use the remove() method to delete a key-value pair.
Example
java id="lhm004"
import java.util.LinkedHashMap;
public class RemoveExample {
public static void main(String[] args) {
LinkedHashMap<String, Integer> inventory = new LinkedHashMap<>();
inventory.put("Monitor", 12);
inventory.put("Printer", 5);
inventory.put("Scanner", 3);
inventory.remove("Printer");
System.out.println(inventory);
}
}
To remove all entries from the map, use the clear() method.
java id="lhm005"
inventory.clear();
Finding the Size of a LinkedHashMap
Use the size() method to determine the number of key-value pairs stored in the map.
Example
java id="lhm006"
import java.util.LinkedHashMap;
public class SizeExample {
public static void main(String[] args) {
LinkedHashMap<String, String> countries = new LinkedHashMap<>();
countries.put("IN", "India");
countries.put("US", "United States");
countries.put("JP", "Japan");
System.out.println("Total Entries: " + countries.size());
}
}
Output
text id="lhmout006"
Total Entries: 3
Note:Only unique keys are counted. Updating the value of an existing key does not increase the size of the map.
Looping Through a LinkedHashMap
You can iterate through a LinkedHashMap using several methods.
Print All Keys
java id="lhm007"
for (String key : departments.keySet()) {
System.out.println(key);
}
Print All Values
java id="lhm008"
for (String value : departments.values()) {
System.out.println(value);
}
Print Keys and Values
Using entrySet() is the recommended and most efficient approach.
java id="lhm009"
import java.util.LinkedHashMap;
import java.util.Map;
public class EntrySetExample {
public static void main(String[] args) {
LinkedHashMap<String, String> departments = new LinkedHashMap<>();
departments.put("HR", "Human Resources");
departments.put("IT", "Information Technology");
departments.put("FIN", "Finance");
for (Map.Entry<String, String> entry : departments.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
Output
text id="lhmout009"
HR -> Human Resources
IT -> Information Technology
FIN -> Finance
Because `LinkedHashMap` preserves insertion order, the entries are displayed in the order they were added.
Tip: Use a `LinkedHashMap` when the order of insertion matters, such as displaying menus, maintaining history, or processing records sequentially.
Using the `var` Keyword (Java 10+)
Starting with Java 10, you can use the `var` keyword for local variable type inference.
Without `var`
java id="lhm010"
LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
With `var`
java id="lhm011"
var scores = new LinkedHashMap<String, Integer>();
Using `var` makes code shorter, although explicit type declarations are often preferred for improved readability.
Declaring a LinkedHashMap Using the Map Interface
A common Java best practice is to declare variables using the Map interface instead of the implementation class.
Example
java id="lhm012"
import java.util.LinkedHashMap;
import java.util.Map;
public class MapInterfaceExample {
public static void main(String[] args) {
Map<String, String> fileTypes = new LinkedHashMap<>();
fileTypes.put("PDF", "Portable Document Format");
fileTypes.put("DOCX", "Microsoft Word Document");
fileTypes.put("PNG", "Portable Network Graphics");
System.out.println(fileTypes);
}
}
Using the Map interface makes your code more flexible because you can replace
LinkedHashMap with another implementation, such as HashMap or TreeMap, without changing the rest of your application.