Home page

Sunday, July 2, 2023

LinkedHashMap in JAVA

In Java, LinkedHashMap is a class that extends the HashMap class and provides a predictable iteration order based on the insertion order of elements. Here's when and why you would use a LinkedHashMap:

Maintaining insertion order: Unlike HashMap, LinkedHashMap maintains the order in which elements are inserted into the map. It provides a predictable iteration order, which can be useful when you need to iterate over the map's elements in the order they were added.

Access-ordered iteration: LinkedHashMap also supports access-ordered iteration in addition to insertion order. With access-ordered mode enabled, the most recently accessed elements are moved to the end of the iteration order. This can be beneficial in scenarios where you frequently access and modify elements, and you want to prioritize recently accessed elements for efficient retrieval.

Iteration performance: LinkedHashMap provides faster iteration performance compared to TreeMap (which maintains a sorted order) since it doesn't require the overhead of maintaining a sorted structure.

Compatibility with existing APIs: LinkedHashMap is compatible with the Map interface and can be used wherever a Map is expected. This makes it a suitable choice when you want to maintain insertion order and leverage the functionality provided by the Map interface.

Here's an example of how to use LinkedHashMap in Java:

import java.util.LinkedHashMap;

import java.util.Map;

public class LinkedHashMapExample {

    public static void main(String[] args) {

        // Create a LinkedHashMap

        LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();

        // Add elements to the LinkedHashMap

        linkedHashMap.put(3, "Apple");

        linkedHashMap.put(2, "Banana");

        linkedHashMap.put(1, "Orange");

        // Iterate over the LinkedHashMap

        for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {

            System.out.println(entry.getKey() + ": " + entry.getValue());

        }

    }

}

In this example, we create a LinkedHashMap called linkedHashMap that maps integers to strings.

We add elements to the LinkedHashMap using the put() method. The elements are added in a specific order.

We iterate over the LinkedHashMap using the entrySet() method, which provides a set view of the mappings. The iteration order is based on the insertion order.

Output:
3: Apple
2: Banana
1: Orange

As shown in the example, LinkedHashMap maintains the order of elements based on their insertion order. This can be useful when you need to preserve the order in which elements were added to the map.

No comments:

Post a Comment