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

  1. import java.util.*;
  2. public class LinkedHashMapPutExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
  6.  
  7. lhm.put(1, "One");
  8. lhm.put(2, "Two");
  9. lhm.put(3, "Three");
  10.  
  11. System.out.println(lhm);
  12.  
  13. }
  14. }
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

  1. import java.util.*;
  2. public class LinkedHashMapPutAllExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
  6.  
  7. lhm.put(1, "One");
  8. lhm.put(2, "Two");
  9. lhm.put(3, "Three");
  10.  
  11. LinkedHashMap<Integer,String>  lhm1 = new LinkedHashMap<>();
  12. lhm1.put(4, "Four");
  13. lhm1.put(5, "Five");
  14.  
  15. lhm.putAll(lhm1);
  16. System.out.println(lhm);
  17.  
  18. }
  19. }
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

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on