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
- 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);
- }
- }
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
- 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);
- }
- }
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
