Add elements in TreeSet

We can use add() and addAll() method of TreeSet to add elements to TreeSet

boolean add(Object obj)

It adds the element obj to the TreeSet.

Example

  1. import java.util.*;
  2. public class TreeSetAddExample {
  3. public static void main(String args[]) {
  4.  
  5. TreeSet<String> ts = new TreeSet<String>();
  6.  
  7. ts.add(“java”);
  8. ts.add(“c”);
  9. ts.add(“c++);
  10. System.out.println(ts);
  11. }
  12. }
import java.util.*;
public class TreeSetAddExample {
public static void main(String args[]) {

TreeSet<String> ts = new TreeSet<String>();

ts.add(“java”);
ts.add(“c”);
ts.add(“c++”);
System.out.println(ts);
}
}


Using addAll() method

We can also add another TreeSet to existing TreeSet using addAll() method

Example

  1. import java.util.*;
  2. public class TreeSetAddAllExample {
  3. public static void main(String args[]) {
  4.  
  5. TreeSet<String> ts = new TreeSet<String>();
  6. TreeSet<String> ts1 = new TreeSet<String>();
  7. ts.add("java");
  8. ts.add("c");
  9. ts.add("c++");
  10.  
  11. ts1.add("python");
  12. ts1.add("oracle");
  13. ts.addAll(ts1);
  14. System.out.println(ts);
  15. }
  16. }
import java.util.*;
public class TreeSetAddAllExample {
public static void main(String args[]) {

TreeSet<String> ts = new TreeSet<String>();
TreeSet<String> ts1 = new TreeSet<String>();
ts.add("java");
ts.add("c");
ts.add("c++");

ts1.add("python");
ts1.add("oracle");
ts.addAll(ts1);
System.out.println(ts);
}
}
Note : We can observe that elements are in sorted order
            Using addAll(), we can also add elements of another collection like list to TreeSet

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