Thursday, September 4, 2025
HomeLanguagesJavaHow to Add Key-Value pairs to LinkedHashMap in Java?

How to Add Key-Value pairs to LinkedHashMap in Java?

LinkedHashMap is a Hash table and linked list implementation of the Map interface. In LinkedHashMap order of key-value pair depends on the order in which keys were inserted into the map. Insertion order does not affect if a key is reinserted into the map.

Example:

Input: 
     Key: 1
     Value : 1221
     Key: 2
     Value : 2112
Output:
    Keys : [1,2]
    Values : [1221,2112]
    Key-Value pairs : [1=1221, 2=2112]

Methods Use:

  1. put(Key, Value): First parameter as key and second parameter as Value.
  2. keySet(): Creates a set out of the key elements contained in the hash map.
  3. values(): Create a set out of the values in the hash map.

Approach:

  1. Create two-variable named as Key and Value
  2. Accept the input from user in Key and in Value
  3. Use put() method to add Key-Value pair inside the LinkedHashMap

Below is the implementation of the above approach:

Java




// Java Program to add key-value 
// pairs to LinkedHashMap
import java.util.*;
public class Main {
    
    public static void main(String[] args)
    {
        // create an instance of LinkedHashMap
        LinkedHashMap<Integer, Integer> map
            = new LinkedHashMap<Integer, Integer>();
  
        int num, key, val;
        num = 2;
        for (int i = 0; i < num; i++) {
            
            // Taking inputs from user
            key = i + 1;
            val = key * 10;
  
            // Add mappings using put method
            map.put(key, val);
        }
        // Displaying key
        System.out.println("Keys: " + map.keySet());
  
        // Displaying value
        System.out.println("Values: " + map.values());
  
        // Displaying key-value pair
        System.out.println("Key-Value pairs: "
                           + map.entrySet());
    }
}


Output

Keys: [1, 2]
Values: [10, 20]
Key-Value pairs: [1=10, 2=20]

Time Complexity: O(1)

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6628 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS