LinkedHashMap in Java

LinkedHashMap is a widely used data structure in the Java programming language. It is a part of the Java Collection Framework and is an implementation of the Map interface. It provides a way to store and retrieve data in the order in which they were added. In this blog post, we will discuss what LinkedHashMap in Java is. How it works. And how to use it in Java.

What is LinkedHashMap in Java?

A LinkedHashMap is a collection that stores key-value pairs. Where each key is unique and is associated with a specific value. LinkedHashMap is implemented using a hash table and a doubly-linked list. Which allows for fast and efficient data retrieval, insertion, and deletion. The doubly-linked list maintains the order in which the elements were added. That means that the elements are iterated in the order in which they were added to the map.

Why use LinkedHashMap in Java?

LinkedHashMap is useful in situations where we need to maintain the order of elements. While also providing the features of a HashMap. It is particularly useful in situations where we need to iterate through the elements in the order in which they were added. Or need to access elements based on their insertion order.

LinkedHashMap is also useful in situations where we need to maintain a cache and need to access the least recently used elements. It provides the removeEldestEntry() method that allows for removing the eldest entry in the map based on the order of insertion, which can be used to implement a cache.

How to use LinkedHashMap in Java?

Using a LinkedHashMap in Java is easy. To create a LinkedHashMap, we first need to import the java.util package, which contains the LinkedHashMap class.

Following is an example of creating a LinkedHashMap in Java and adding data to it:

import java.util.LinkedHashMap;

LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);

The output of the above example is given below:

{one=1, two=2, three=3}

Once we have created the LinkedHashMap, we can add data to it using the put() method. The put() method takes two parameters: the is parameter is key and the second one is value. In the example above, we are adding three key-value pairs to the LinkedHashMap. As we can see, the elements are stored in the order in which they were added.

We can also retrieve data from a LinkedHashMap using the get() method. For example, to retrieve the value associated with the key “two”, we can use the following code:

Integer value = map.get("two");

The output of the above example is:

2

LinkedHashMap also provides several other useful methods such as entrySet(), keySet(), and values() to access the elements in the map.

In addition to these methods, LinkedHashMap also provides other useful methods such as remove(), clear(), and size() that work similar to the HashMap.

Reference: LinknedHashMap