Let’s learn TreeMap putAll() method in java.
TreeMap putAll() method in java
putAll() method of TreeMap class copies all of the mappings from the specified map to this map.
These mappings replace any mappings that this map had for any of the keys currently in the specified map.
Syntax:
public void putAll(Map<? extends K,? extends V> map)
Parameters:
map mappings to be stored in this map.
Throws:
ClassCastException – if the class of a key or value in the specified map prevents it from being stored in this map.
NullPointerException – if the specified map is null or the specified map contains a null key and this map does not permit null keys.
Now let’s see example on TreeMap putAll() method.
import java.util.TreeMap; public class TreeMapPutAllMethodExample { public static void main(String[] args) { TreeMap<Integer, String> tm1 = new TreeMap<Integer, String>(); tm1.put(32, "pineapple"); tm1.put(51, "watermelon"); tm1.put(38, "grapes"); tm1.put(69, "mango"); tm1.put(58, "apple"); System.out.println("TreeMap before using putAll() method: " + tm1); // create new TreeMap and copy TreeMap<Integer, String> tm2 = new TreeMap<Integer, String>(); tm2.putAll(tm1); System.out.println("TreeMap after using putAll() method: " + tm2); } }
Output:
TreeMap before using putAll() method: {32=pineapple, 38=grapes, 51=watermelon, 58=apple, 69=mango}
TreeMap after using putAll() method: {32=pineapple, 38=grapes, 51=watermelon, 58=apple, 69=mango}
Also read – abstraction in java