How to Print all Mappings of the LinkedHashMap in Java?


In Java, a LinkedHashMap is a popular data structure that combines the advantages of a doubly linked list with a hash map. The elements are retrieved in the same order as they were added since it preserves the sequence of insertion. When we need to iterate over the key-value pairs in a specified sequence, LinkedHashMaps are especially helpful. There are several methods accessible in situations where we want to print every mapping contained in a LinkedHashMap. In this article, we will examine two different methods for efficiently printing all LinkedHashMap's mappings in Java, each having its own benefits and sample code.

Approaches

  • Utilizing the entrySet() method.

  • Utilizing the forEach() method.

Let us look into both approaches: -

Approach-1: Utilizing the entrySet() method.

The entrySet() function offered by the LinkedHashMap class is the initial way for publishing all mappings in a LinkedHashMap. A set of Map is the result of this procedure. The key-value pairs in the LinkedHashMap are contained in entry objects. We can quickly access and display every mapping in this collection by iterating over it.

The entry set is obtained from the LinkedHashMap and iterated over using a for-each loop in this method. We use the getKey() and getValue() methods, respectively, to obtain the key and value for each element. All of the mappings in the LinkedHashMap can be seen by displaying the key-value pairs during the loop.

Algorithm

Step-1: Import the required packages.

Step 2: LinkedHashMap objects can be created.

Step-3: LinkedHashMap key-value pairs should be inserted.

Step-4: Utilize the entrySet() function to get a collection of all key-value mappings.

Step-5: Repeat the set's steps.

Step-6: Please print the key and value for each entry in the set.

Example

//import the required package
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) {
        // Create a LinkedHashMap
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();

        // Insert key-value pairs
        linkedHashMap.put("Pen", 10);
        linkedHashMap.put("Rubber", 5);
        linkedHashMap.put("Paper", 8);
        linkedHashMap.put("File", 20);

        // Print all mappings with the help of entrySet()
        for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Output

Key: Pen, Value: 10
Key: Rubber, Value: 5
Key: Paper, Value: 8
Key: File, Value: 20

Approach-2: Utilizing the forEach() method.

With the introduction of Java 8, the LinkedHashMap class added the forEach() method, which enables us to quickly perform an operation on each key-value pair. This method uses a lambda expression and the forEach() method to output every mapping in a LinkedHashMap.

In this method, the LinkedHashMap object's forEach() method is immediately called. We define the printing logic in the lambda expression, where we concatenate the key and value to get the required output. As it does away with the requirement for an explicit iteration loop, this method is very helpful when we desire a more concise and functional style of coding.

Algorithm

Step-1: Import the necessary package and then create the class named Main. Construct a LinkedHashMap object.

Step-2: To the LinkedHashMap, add key-value pairs.

Step-3: To go through each entry, employ the forEach() method.

Step-4: In the end print the key and value for each entry.

Example

//import the required package
import java.util.LinkedHashMap;

public class Main {

    public static void main(String[] args) {
        // Create a LinkedHashMap
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();

        // Insert key-value pairs
        linkedHashMap.put("Pen", 10);
        linkedHashMap.put("Rubber", 5);
        linkedHashMap.put("Paper", 8);
        linkedHashMap.put("File", 20);

        // Print all mappings one by one
        linkedHashMap.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output

Key: Pen, Value: 10
Key: Rubber, Value: 5
Key: Paper, Value: 8
Key: File, Value: 20

Conclusion

The entrySet() method or the forEach() method in Java can be used to print every mapping in a LinkedHashMap. Employing the key-value mappings provided by the entrySet() method, we can iterate through each entry and report the desired results. The forEach() method, on the other hand, streamlines the procedure by accepting a lambda expression to carry out the printing task. Two approaches are depicted in this article. Both approaches are effective and deliver the desired outcomes. Pick the option that best fits your coding needs and preferences.

Updated on: 25-Aug-2023

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements