English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java HashMap putAll() method will put all keys/The value mappings from the specified Map are inserted into the HashMap.
The syntax of the putAll() method is:
hashmap.putAll(Map m)
map - A map containing the mappings to be inserted into the hashmap
The putAll() method does not return any value.
Note: If the map contains any keys that already exist in the hash map. Then, the new value associated with the key will replace the previous value in the hashmap.
import java.util.HashMap; class Main { public static void main(String[] args){ //Create a HashMap HashMap<String, Integer> primeNumbers = new HashMap<>(); //Add the mapping to the HashMap primeNumbers.put("Two", 2); primeNumbers.put("Three", 3); System.out.println("Prime Numbers: " + primeNumbers); //Create another HashMap HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Four", 4); //Add all mappings from primeNumbers to numbers numbers.putAll(primeNumbers); System.out.println("Numbers: " + numbers); } }
Output Result
Prime Numbers: {Two=2, Three=3} Numbers: {One=1, Four=4, Two=2, Three=3}
In the above example, we created two hash maps named primeNumbers and numbers. Note this line,
numbers.putAll(primeNumbers);
Here, the putAll() method adds all mappings from primeNumbers to numbers.
Note:We have used the put() method to add a single mapping to the hashmap. For more information, please visitJava HashMap put()。
import java.util.HashMap; import java.util.TreeMap; class Main { public static void main(String[] args){ //Create a String type TreeMap TreeMap<String, String> treemap = new TreeMap<>(); //Add the mapping to the TreeMap treemap.put("A", "Apple"); treemap.put("B", "Ball"); treemap.put("C", "Cat"); System.out.println("TreeMap: " + treemap); //Create a HashMap HashMap<String, String> hashmap = new HashMap<>(); //Add the mapping to the HashMap hashmap.put("Y", "Yak"); hashmap.put("Z", "Zebra"); System.out.println("Initial HashMap:", + hashmap); // Add all mappings from TreeMap to HashMap hashmap.putAll(treemap); System.out.println("Updated HashMap:", + hashmap); } }
Output Result
TreeMap: {A=Apple, B=Ball, C=Cat} Initial HashMap: {Y=Yak, Z=Zebra} Updated HashMap: {A=Apple, B=Ball, C=Cat, Y=Yak, Z=Zebra}
In the above example, we created a TreeMap and a HashMap. Note this line,
hashmap.putAll(treemap);
Here, we use the putAll() method to add all mappings from TreeMap to HashMap.