Let’s learn TreeSet addAll() method in java.
TreeSet addAll() method in java
addAll() method of TreeSet class adds all of the elements in the specified collection to this set.
Syntax:
public boolean addAll(Collection<? extends E> c)
Parameters:
c collection containing elements to be added to this set.
Returns:
true if this set changed as a result of the call.
Throws:
ClassCastException – if the elements provided cannot be compared with the elements currently in the set.
NullPointerException – if the specified collection is null or if any element is null and this set uses natural ordering, or its comparator does not permit null elements.
Also read – TreeSet in java
Now let’s see example on TreeSet addAll(Collection<? extends E> c) method.
import java.util.Iterator; import java.util.TreeSet; public class TreeSetAddAllMethodExample { public static void main(String[] args) { TreeSet<Integer> ts1 = new TreeSet<Integer>(); TreeSet<Integer> ts2 = new TreeSet<Integer>(); // add in TreeSet ts1 ts1.add(23); ts1.add(24); ts1.add(25); // add in TreeSet ts2 ts2.add(26); ts2.add(27); ts2.add(28); // add ts2 to ts1 ts1.addAll(ts2); // create an iterator Iterator<Integer> iterate = ts1.iterator(); // displaying the Tree set data System.out.print("TreeSet values: "); while(iterate.hasNext()) { System.out.print(iterate.next() + " "); } } }
Output:
TreeSet values: 23 24 25 26 27 28