Add elements in LinkedHashMap
We can use put() and putAll() methods of LinkedHashMap to add elements to LinkedHashMap
Object put(Object key, Object value);
Associates the specified value with the specified key in this map.
This method is used to add single key-value pair to the LinkedHashMap
Example
- import java.util.*;
- public class LinkedHashMapPutExample {
- public static void main(String args[]) {
- LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
- lhm.put(1, "One");
- lhm.put(2, "Two");
- lhm.put(3, "Three");
- System.out.println(lhm);
- }
- }
import java.util.*; public class LinkedHashMapPutExample { public static void main(String args[]) { LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>(); lhm.put(1, "One"); lhm.put(2, "Two"); lhm.put(3, "Three"); System.out.println(lhm); } }
void putAll(Map m);
Copies all of the mappings from the specified map to this map.
This method is used to add all key-value pairs from another Map to this Map
Example
- import java.util.*;
- public class LinkedHashMapPutAllExample {
- public static void main(String args[]) {
- LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
- lhm.put(1, "One");
- lhm.put(2, "Two");
- lhm.put(3, "Three");
- LinkedHashMap<Integer,String> lhm1 = new LinkedHashMap<>();
- lhm1.put(4, "Four");
- lhm1.put(5, "Five");
- lhm.putAll(lhm1);
- System.out.println(lhm);
- }
- }
import java.util.*; public class LinkedHashMapPutAllExample { public static void main(String args[]) { LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>(); lhm.put(1, "One"); lhm.put(2, "Two"); lhm.put(3, "Three"); LinkedHashMap<Integer,String> lhm1 = new LinkedHashMap<>(); lhm1.put(4, "Four"); lhm1.put(5, "Five"); lhm.putAll(lhm1); System.out.println(lhm); } }
Note : We can see that lhm1 has 2 key-value pairs and these 2 are added to main LinkedHashMap using putAll() method