1. Introduction
In this tutorial, you will learn:
- What is LinkedHashMap?
- Key Points About LinkedHashMap
- Creating a LinkedHashMap and Adding Elements
- Accessing Elements in a LinkedHashMap
- Modifying Elements in a LinkedHashMap
- Removing Elements from a LinkedHashMap
- Iterating Over a LinkedHashMap
- Searching for Elements in a LinkedHashMap
- LinkedHashMap of User-Defined Objects
- Common LinkedHashMap Methods
- Conclusion
1. What is LinkedHashMap?
LinkedHashMap
in Java is a part of the Java Collections Framework and implements the Map
interface. It is a hash table and linked list implementation of the Map
interface, with predictable iteration order. LinkedHashMap
maintains a doubly-linked list running through all of its entries, which defines the iteration order as the order in which elements were inserted or accessed.
LinkedHashMap is a part of Java’s collections framework. It inherits from HashMap, meaning it shares many of the same functionalities but with the added benefit of maintaining insertion order.
A LinkedHashMap cannot contain duplicate keys. Just like HashMap, the LinkedHashMap does not allow duplicate keys. Each key in the map must be unique, and if a key already exists, its value will be replaced with the new one.
LinkedHashMap can have null values and the null key. Similar to HashMap
, LinkedHashMap allows one null
key and can store multiple null
values. This flexibility is useful when you need to map something to null
or represent a missing value.
The iteration order in a LinkedHashMap is normally the order in which the elements are inserted (insertion order). One of the most useful features of LinkedHashMap is that it maintains insertion order. This means that when you iterate over the entries, they will be returned in the same order that they were inserted.
Just like HashMap, LinkedHashMap is not thread-safe. By default, LinkedHashMap is not thread-safe. If multiple threads are accessing a LinkedHashMap concurrently and at least one thread modifies it, you must synchronize it manually to avoid unexpected behavior.
3. Creating a LinkedHashMap and Adding Elements
To create a LinkedHashMap
, you can use the LinkedHashMap
constructor. You can then use methods such as put
to add key-value pairs to the map.
Example:
In this example, we create a LinkedHashMap
of strings and integers and add a few key-value pairs to it.
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
public static void main(String[] args) {
// Creating a LinkedHashMap
Map<String, Integer> map = new LinkedHashMap<>();
// Adding elements to the LinkedHashMap
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
map.put(null, 4); // Null key
map.put("Date", null); // Null value
// Displaying the LinkedHashMap
System.out.println("LinkedHashMap: " + map);
}
}
Output:
LinkedHashMap: {Apple=1, Banana=2, Cherry=3, null=4, Date=null}
4. Accessing Elements in a LinkedHashMap
You can access elements in a LinkedHashMap
using the get
method by providing the key.
Example:
In this example, we demonstrate how to access elements in a LinkedHashMap
.
import java.util.LinkedHashMap;
import java.util.Map;
public class AccessLinkedHashMap {
public static void main(String[] args) {
// Creating a LinkedHashMap
Map<String, Integer> map = new LinkedHashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Accessing elements
System.out.println("Value for 'Banana': " + map.get("Banana"));
System.out.println("Value for 'Mango': " + map.get("Mango")); // Key not present
}
}
Output:
Value for 'Banana': 2
Value for 'Mango': null
5. Modifying Elements in a LinkedHashMap
You can modify elements in a LinkedHashMap
using the put
method, which will replace the value for the given key if it already exists.
Example:
In this example, we demonstrate how to modify elements in a LinkedHashMap
.
import java.util.LinkedHashMap;
import java.util.Map;
public class ModifyLinkedHashMap {
public static void main(String[] args) {
// Creating a LinkedHashMap
Map<String, Integer> map = new LinkedHashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Modifying an element
map.put("Banana", 4); // Updating value for key "Banana"
// Displaying the updated LinkedHashMap
System.out.println("Updated LinkedHashMap: " + map);
}
}
Output:
Updated LinkedHashMap: {Apple=1, Banana=4, Cherry=3}
6. Removing Elements from a LinkedHashMap
You can remove elements from a LinkedHashMap
using methods such as remove
and clear
.
Example:
In this example, we demonstrate how to remove elements from a LinkedHashMap
.
import java.util.LinkedHashMap;
import java.util.Map;
public class RemoveLinkedHashMap {
public static void main(String[] args) {
// Creating a LinkedHashMap
Map<String, Integer> map = new LinkedHashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Removing an element
map.remove("Banana");
// Displaying the LinkedHashMap after removal
System.out.println("LinkedHashMap after removal: " + map);
// Clearing the LinkedHashMap
map.clear();
System.out.println("LinkedHashMap after clearing: " + map);
}
}
Output:
LinkedHashMap after removal: {Apple=1, Cherry=3}
LinkedHashMap after clearing: {}
7. Iterating Over a LinkedHashMap
You can iterate over a LinkedHashMap
using various methods such as a simple for-each loop, entrySet
, and keySet
.
Example:
In this example, we demonstrate different ways to iterate over a LinkedHashMap
.
import java.util.LinkedHashMap;
import java.util.Map;
public class IterateLinkedHashMap {
public static void main(String[] args) {
// Creating a LinkedHashMap
Map<String, Integer> map = new LinkedHashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Using for-each loop with entrySet
System.out.println("Using for-each loop with entrySet:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Using for-each loop with keySet
System.out.println("Using for-each loop with keySet:");
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
// Using forEach method (Java 8 and later)
System.out.println("Using forEach method:");
map.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
Output:
Using for-each loop with entrySet:
Apple: 1
Banana: 2
Cherry: 3
Using for-each loop with keySet:
Apple: 1
Banana: 2
Cherry: 3
Using forEach method:
Apple: 1
Banana: 2
Cherry: 3
8. Searching for Elements in a LinkedHashMap
You can search for elements in a LinkedHashMap
using methods such as containsKey
and containsValue
.
Example:
In this example, we demonstrate how to check if a LinkedHashMap
contains a specific key or value.
import java.util.LinkedHashMap;
import java.util.Map;
public class SearchLinkedHashMap {
public static void main(String[] args) {
// Creating a LinkedHashMap
Map<String, Integer> map = new LinkedHashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Check if the LinkedHashMap contains a specific key
System.out.println("Does the LinkedHashMap contain 'Banana'? " + map.containsKey("Banana"));
System.out.println("Does the LinkedHashMap contain 'Mango'? " + map.containsKey("Mango"));
// Check if the LinkedHashMap contains a specific value
System.out.println("Does the LinkedHashMap contain value 3? " + map.containsValue(3));
System.out.println("Does the LinkedHashMap contain value 4? " + map.containsValue(4));
}
}
Output:
Does the LinkedHashMap contain 'Banana'? true
Does the LinkedHashMap contain 'Mango'? false
Does the LinkedHashMap contain value 3? true
Does the LinkedHashMap contain value 4? false
9. LinkedHashMap of User-Defined Objects
You can use LinkedHashMap
to store user-defined objects as keys or values. This involves creating a class for the objects you want to store and ensuring that the equals
and hashCode
methods are properly overridden for keys.
Example:
In this example, we create a Person
class and then create a LinkedHashMap
to store Person
objects as keys.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class UserDefinedObjectLinkedHashMap {
public static void main(String[] args) {
// Creating a LinkedHashMap with Person objects as keys
Map<Person, String> map = new LinkedHashMap<>();
map.put(new Person("Alice", 30), "Engineer");
map.put(new Person("Bob", 25), "Designer");
map.put(new Person("Charlie", 35), "Manager");
// Displaying the LinkedHashMap
for (Map.Entry<Person, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output:
Person{name='Alice', age=30}: Engineer
Person{name='Bob', age=25}: Designer
Person{name='Charlie', age=35}: Manager
10. All LinkedHashMap Class Methods
- Java LinkedHashMap put() Method
- Java LinkedHashMap clear() Method
- Java LinkedHashMap clone() Method
- Java LinkedHashMap containsKey() Method
- Java LinkedHashMap get() Method
- Java LinkedHashMap isEmpty() Method
- Java LinkedHashMap putAll() Method
- Java LinkedHashMap remove(Object key) Method
- Java LinkedHashMap size() Method
- Java LinkedHashMap entrySet() Method
- Java LinkedHashMap keySet() Method
- Java LinkedHashMap values() Method
- Java LinkedHashMap getOrDefault() Method
- Java LinkedHashMap replace(K key, V oldValue, V newValue) Method
- Java LinkedHashMap replace(K key, V value) Method
- Java LinkedHashMap forEach() Method
- Java LinkedHashMap replaceAll() Method
- Java LinkedHashMap computeIfAbsent() Method
- Java LinkedHashMap merge() Method
- Java LinkedHashMap keySpliterator() Method
- Java LinkedHashMap valueSpliterator() Method
- Java LinkedHashMap entrySpliterator() Method
- Java LinkedHashMap valueStream() Method
- Java LinkedHashMap entryStream() Method
11. Summary: Key Points About LinkedHashMap
- Stores data in key-value pairs.
- A LinkedHashMap cannot contain duplicate keys.
- Allows one null key and multiple null values.
- Maintains insertion order or access order.
- Uses a hash table for storage.
- LinkedHashMap is not a thread-safe by default.