1. Introduction

In Java, the LinkedHashMap class is part of the Java Collections Framework and inherits HashMap class. The LinkedHashMap maintains the insertion order, which means upon displaying LinkedHashMap content, you’ll get the elements in the order they were inserted. In this post, we will demonstrate how to add elements to a LinkedHashMap.

2. Program Steps

1. Create a new LinkedHashMap instance.

2. Use the put method to add key-value pairs to the LinkedHashMap.

3. Display the contents of the LinkedHashMap to see the elements in their insertion order.

3. Code Program

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapAddElement {

    public static void main(String[] args) {

        // Step 1: Create a new LinkedHashMap instance
        LinkedHashMap<String, Integer> fruitsPriceMap = new LinkedHashMap<>();

        // Step 2: Use the put method to add key-value pairs to the LinkedHashMap
        fruitsPriceMap.put("Apple", 50);
        fruitsPriceMap.put("Banana", 30);
        fruitsPriceMap.put("Orange", 60);

        // Step 3: Display the contents of the LinkedHashMap
        System.out.println("Contents of the LinkedHashMap:");
        for (Map.Entry<String, Integer> entry : fruitsPriceMap.entrySet()) {
            System.out.println(entry.getKey() + " costs " + entry.getValue() + " cents");
        }
    }
}

Output:

Contents of the LinkedHashMap:
Apple costs 50 cents
Banana costs 30 cents
Orange costs 60 cents

4. Step By Step Explanation

Step 1: We initialize a LinkedHashMap named fruitsPriceMap to store fruit names as keys and their respective prices as values.

Step 2: Using the put method, we add three key-value pairs (fruit name and its price) to the LinkedHashMap.

Step 3: By iterating over the LinkedHashMap using an enhanced for loop, we print its content. As observed in the output, the elements are displayed in the order they were inserted, demonstrating the insertion-order preservation characteristic of LinkedHashMap.