Home Java TreeSet Methods addAll() Java TreeSet addAll() Method Definition In Java, addAll(c) inserts every element of collection c into the TreeSet, sorting them and skipping duplicates automatically.
It returns true if at least one new element was added. If c is empty or every item in c is already in the set, it returns false.
An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe .
Syntax Pass any Collection whose elements are compatible with this set's element type and ordering.
TreeSet<String> club = new TreeSet<>(Arrays.asList("Mia", "Leo"));
List<String> newcomers = Arrays.asList("Leo", "Ava", "Zoe");
boolean changed = club.addAll(newcomers); // true -> [Ava, Leo, Mia, Zoe] Call What it does set.addAll(list)Deduplicates and sorts elements from a list into the set. set.addAll(otherSet)Forms the union of two sets. new TreeSet<>(list)Builds a new sorted set directly from a collection. Collections.addAll(set, "a", "b")Adds individual values without creating a list first.
When adding a SortedSet with the same comparator into an empty TreeSet, the JDK builds the tree in linear time rather than inserting element by element.
Library declarations // java.util.TreeSet<E>
public boolean addAll(Collection<? extends E> c)
// Declared in Set<E> and Collection<E> Parameters Parameter Description c (Collection<? extends E>)The collection whose elements will be added. Must not be null.
Return Value Return Value Description trueAt least one new element was added and the set grew. falsec was empty or every element in c already existed in the set.
Important
Passing null throws NullPointerException. A null element inside c also throws NullPointerException under natural ordering, and incompatible types throw ClassCastException. If an exception happens partway through, earlier elements from c remain in the set.
Compare with Similar Methods Ways to bulk-insert or combine sets:
Java Examples 1. Merge club rosters 2. Detect new arrivals 3. Comparator and nulls Example 1 — Merge Two Club Rosters and Sort Alphabetically Combine an existing robotics club roster with sign-ups from an array-backed list, ignoring repeats.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class TreeSetAddAllRosters {
public static void main(String[] args) {
TreeSet<String> members = new TreeSet<>(Arrays.asList("Noah", "Aria"));
List<String> signups = Arrays.asList("Aria", "Liam", "Maya", "Liam");
boolean added = members.addAll(signups);
System.out.println("set changed? " + added);
System.out.println("roster: " + members);
System.out.println("source untouched: " + signups);
}
} set changed? true
roster: [Aria, Liam, Maya, Noah]
source untouched: [Aria, Liam, Maya, Liam] How It Works Duplicates dropped on arrival. Both "Aria" (already in the club) and the second "Liam" are skipped automatically.Sorted result. The remaining unique names are inserted in natural alphabetical order: Aria, Liam, Maya, Noah.Source list stays unchanged. addAll() only reads signups, leaving its four elements intact.Example 2 — Check Whether addAll() Actually Added Anything New Test the return value when adding an empty list, all duplicates, and a mix containing one new score.
import java.util.Arrays;
import java.util.Collections;
import java.util.TreeSet;
public class TreeSetAddAllReturn {
public static void main(String[] args) {
TreeSet<Integer> scores = new TreeSet<>(Arrays.asList(50, 70, 90));
System.out.println("empty list: " + scores.addAll(Collections.<Integer>emptyList()));
System.out.println("all existing: " + scores.addAll(Arrays.asList(50, 90)));
System.out.println("one new (80): " + scores.addAll(Arrays.asList(70, 80)));
System.out.println("final scores: " + scores);
}
} empty list: false
all existing: false
one new (80): true
final scores: [50, 70, 80, 90] How It Works Empty input changes nothing. Passing an empty list inserts zero elements, so addAll() returns false.Repeated elements also return false. Since 50 and 90 are already present, the tree stays unchanged.One new element is enough. Adding [70, 80] skips 70, inserts 80 between 70 and 90, and returns true.Example 3 — Merge Into a Reversed Set and Guard Against null Merge scores into a descending TreeSet, then see how a null collection or null item throws.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
public class TreeSetAddAllErrors {
public static void main(String[] args) {
TreeSet<Integer> topScores = new TreeSet<>(Comparator.reverseOrder());
topScores.addAll(Arrays.asList(15, 40, 25));
System.out.println("descending: " + topScores);
try {
topScores.addAll(null);
} catch (NullPointerException e) {
System.out.println("null collection: " + e.getClass().getSimpleName());
}
List<Integer> badBatch = Arrays.asList(30, null, 10);
try {
topScores.addAll(badBatch);
} catch (NullPointerException e) {
System.out.println("null element threw: " + e.getClass().getSimpleName());
}
System.out.println("partial batch kept 30: " + topScores);
}
} descending: [40, 25, 15]
null collection: NullPointerException
null element threw: NullPointerException
partial batch kept 30: [40, 30, 25, 15] How It Works Target ordering applies. The target set uses reverseOrder(), so all imported numbers arrange from 40 down to 15.Null collection rejected upfront. Calling addAll(null) throws NullPointerException right away.Not atomic on failure. 30 was inserted before null caused NullPointerException, so 30 stays in topScores.Frequently Asked Questions What does TreeSet addAll() return? It returns true if at least one element from the collection was added to the TreeSet, or false if the set did not change.
Does TreeSet addAll() remove duplicates from a list? Yes. Any duplicate values in the input collection or already in the set are skipped, and the set keeps only unique elements in sorted order.
What happens if the collection passed to addAll() is null? It throws NullPointerException. Pass an empty collection instead if you have no items to add.
Does addAll() keep the TreeSet comparator? Yes. Every added element is sorted using the target TreeSet comparator (or natural ordering if none was given).
What happens if an element inside the collection is null? With natural ordering, addAll() throws NullPointerException when it reaches the null element, leaving any earlier added elements in the set.
Next: ceiling() Find the smallest element greater than or equal to a target, or null.
ceiling() tutorial → About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful
Helpful Share Copy link Suggestion