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

  1. import java.util.*;
  2. public class TreeMapPutExample {
  3. public static void main(String args[]) {
  4.  
  5. TreeMap<Integer,String> tm = new TreeMap<>();
  6.  
  7. tm.put(3, “Three”);
  8. tm.put(1, “One”);
  9. tm.put(2, “Two”);
  10.  
  11.  
  12. System.out.println(tm);
  13.  
  14. }
  15. }
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

  1. import java.util.*;
  2. public class TreeMapPutAllExample {
  3. public static void main(String args[]) {
  4.  
  5. TreeMap<Integer,String> tm = new TreeMap<>();
  6.  
  7. tm.put(1, “One”);
  8. tm.put(2, “Two”);
  9. tm.put(3, “Three”);
  10.  
  11. TreeMap<Integer,String> tm1 = new TreeMap<>();
  12. tm1.put(4, “Four”);
  13. tm1.put(5, “Five”);
  14.  
  15. tm.putAll(tm1);
  16. System.out.println(tm);
  17.  
  18. }
  19. }
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

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