Add elements in HashMap

We can use put() and putAll() methods of HashMap to add elements to HashMap

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 HashMap

Example

  1. import java.util.*;
  2. public class HashMapPutExample {
  3. public static void main(String args[]) {
  4.  
  5. HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
  6.  
  7.       hashMap.put(1, "One");
  8.       hashMap.put(2, "Two");
  9.       hashMap.put(3, "Three");
  10.      
  11.  
  12. System.out.println(hashMap);
  13.  
  14. }
  15. }
import java.util.*;
public class HashMapPutExample {
public static void main(String args[]) {

HashMap<Integer, String> hashMap = new HashMap<Integer, String>();

      hashMap.put(1, "One");
      hashMap.put(2, "Two");
      hashMap.put(3, "Three");
      

System.out.println(hashMap);

}
}


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 HashMap

Example

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

HashMap<Integer, String> hashMap = new HashMap<Integer, String>();

      hashMap.put(1, "One");
      hashMap.put(2, "Two");
      hashMap.put(3, "Three");
      
HashMap<Integer, String> hashMap1 = new HashMap<Integer, String>();
hashMap1.put(4, "Four");
      hashMap1.put(5, "Five");

hashMap.putAll(hashMap1);
System.out.println(hashMap);

}
}
Note : We can see that hashMap1 has 2 key-value pairs and these 2 are added to main HashMap 
            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