LinkedHashMap in Java

LinkedHashMap is a class in Java that extends the HashMap class and provides a hash table that is ordered according to the insertion order of the elements. LinkedHashMap is implemented as a doubly linked list and a hash table. It maintains the elements in the insertion order by keeping a linked list of the elements in the order they were inserted, and it maintains a hash table to enable fast access to the elements by their keys.

Features of LinkedHashMap

  1. Maintains Insertion Order: One of the main features of LinkedHashMap is that it maintains the order of insertion of elements. This is achieved by maintaining a doubly linked list of the elements in the order they were inserted.

  2. Implements Map Interface: LinkedHashMap implements the Map interface, which means it has all the methods of the Map interface, such as put(), get(), remove(), size(), containsKey(), etc.

  3. Allows Null Values and Keys: LinkedHashMap allows null values and null keys, which means you can insert null values and keys into a LinkedHashMap.

  4. Iteration Order: LinkedHashMap can be iterated in two ways: the order of insertion and the order of access. By default, it iterates in the order of insertion, but you can change the iteration order to the order of access by using a constructor that takes a boolean argument.

  5. Slower than HashMap: Since LinkedHashMap maintains the order of insertion, it is slightly slower than HashMap.

Let's see an example of using a LinkedHashMap in Java

import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
  public static void main(String[] args) {
    // Create a LinkedHashMap
    Map<String, Integer> map = new LinkedHashMap<>();
    // Insert some elements into the LinkedHashMap
    map.put("John", 25);
    map.put("Alice", 30);
    map.put("Bob", 20);
    map.put("Charlie", 35);
    // Print the elements of the LinkedHashMap
    System.out.println("Elements of LinkedHashMap:");
    System.out.println(map);
    // Access an element of the LinkedHashMap
    System.out.println("Age of Bob: " + map.get("Bob"));
  }
}

Output:

Elements of LinkedHashMap:
{John=25, Alice=30, Bob=20, Charlie=35}
Age of Bob: 20

In the above example, we have created a LinkedHashMap that stores the ages of some people. We have inserted some elements into the LinkedHashMap using the put() method. We have printed the elements of the LinkedHashMap using the println() method. We have also accessed an element of the LinkedHashMap using the get() method. As you can see from the output, the LinkedHashMap maintains the order of insertion of the elements.