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:
- put(Key, Value): First parameter as key and second parameter as Value.
- keySet(): Creates a set out of the key elements contained in the hash map.
- values(): Create a set out of the values in the hash map.
Approach:
- Create two-variable named as Key and Value
- Accept the input from user in Key and in Value
- Use put() method to add Key-Value pair inside the LinkedHashMap
Below is the implementation of the above approach:
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
LinkedHashMap<Integer, Integer> map
= new LinkedHashMap<Integer, Integer>();
int num, key, val;
num = 2 ;
for ( int i = 0 ; i < num; i++) {
key = i + 1 ;
val = key * 10 ;
map.put(key, val);
}
System.out.println( "Keys: " + map.keySet());
System.out.println( "Values: " + map.values());
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)
Last Updated :
22 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...