Java TreeSet addAll() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

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.

Java
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]
CallWhat 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
// java.util.TreeSet<E>
public boolean addAll(Collection<? extends E> c)

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
c (Collection<? extends E>)The collection whose elements will be added. Must not be null.

Return Value

Return ValueDescription
trueAt least one new element was added and the set grew.
falsec was empty or every element in c already existed in the set.

Compare with Similar Methods

Ways to bulk-insert or combine sets:

MethodHow it differs
add(e)Adds a single element instead of a whole collection.
remove(o)Deletes an element instead of merging.
Collections.addAll(c, ...)Adds loose varargs elements directly into the set.
ArrayList.addAll(c)Appends all elements in order without sorting or deduplicating.

Java Examples

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.

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

How It Works

  1. Duplicates dropped on arrival. Both "Aria" (already in the club) and the second "Liam" are skipped automatically.
  2. Sorted result. The remaining unique names are inserted in natural alphabetical order: Aria, Liam, Maya, Noah.
  3. 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.

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

How It Works

  1. Empty input changes nothing. Passing an empty list inserts zero elements, so addAll() returns false.
  2. Repeated elements also return false. Since 50 and 90 are already present, the tree stays unchanged.
  3. 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.

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

How It Works

  1. Target ordering applies. The target set uses reverseOrder(), so all imported numbers arrange from 40 down to 15.
  2. Null collection rejected upfront. Calling addAll(null) throws NullPointerException right away.
  3. Not atomic on failure. 30 was inserted before null caused NullPointerException, so 30 stays in topScores.

Frequently Asked Questions

It returns true if at least one element from the collection was added to the TreeSet, or false if the set did not change.
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.
It throws NullPointerException. Pass an empty collection instead if you have no items to add.
Yes. Every added element is sorted using the target TreeSet comparator (or natural ordering if none was given).
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

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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