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
- 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);
- }
- }
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
- 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);
- }
- }
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

