Add elements in TreeMap
We can use put() and putAll() methods of TreeMap to add elements to TreeMap
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 TreeMap
Example
- import java.util.*;
- public class TreeMapPutExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(3, “Three”);
- tm.put(1, “One”);
- tm.put(2, “Two”);
- System.out.println(tm);
- }
- }
import java.util.*;
public class TreeMapPutExample {
public static void main(String args[]) {
TreeMap<Integer,String> tm = new TreeMap<>();
tm.put(3, “Three”);
tm.put(1, “One”);
tm.put(2, “Two”);
System.out.println(tm);
}
}
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 TreeMap
Example
- import java.util.*;
- public class TreeMapPutAllExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(1, “One”);
- tm.put(2, “Two”);
- tm.put(3, “Three”);
- TreeMap<Integer,String> tm1 = new TreeMap<>();
- tm1.put(4, “Four”);
- tm1.put(5, “Five”);
- tm.putAll(tm1);
- System.out.println(tm);
- }
- }
import java.util.*;
public class TreeMapPutAllExample {
public static void main(String args[]) {
TreeMap<Integer,String> tm = new TreeMap<>();
tm.put(1, “One”);
tm.put(2, “Two”);
tm.put(3, “Three”);
TreeMap<Integer,String> tm1 = new TreeMap<>();
tm1.put(4, “Four”);
tm1.put(5, “Five”);
tm.putAll(tm1);
System.out.println(tm);
}
}Note : We can see that tm1 has 2 key-value pairs and these 2 are added to main TreeMap using putAll() method
