Last Updated : 11 Jul, 2025
The addAll() method of Java AbstractCollection is used to append all elements from a given collection to the current collection. If the collection being appended is a TreeSet, the elements are stored in sorted order, as TreeSet maintains a natural ordering. It is important to note that AbstractCollection cannot be instantiated directly, so we use Collection as the type instead.
Example 1: Adding Elements from One Collection to Another
In this example, we append all the elements from one collection to another using the addAll() method.
Java
import java.util.*;
public class Geeks {
public static void main(String args[]) {
// Creating an empty collection
// (TreeSet maintains elements in sorted order)
Collection<String> c1 = new TreeSet<>();
// Adding elements to the collection
c1.add("Welcome");
c1.add("To");
c1.add("Geeks");
c1.add("4");
c1.add("Geeks"); // Duplicate, will be removed
c1.add("TreeSet");
System.out.println("Collection 1: " + c1);
// Creating another empty Collection
Collection<String> c2 = new TreeSet<>();
// Displaying the empty Collection
System.out.println("Collection 2 (before addAll): " + c2);
// Using addAll() method to append elements
c2.addAll(c1);
// Displaying the Collection after adding elements
System.out.println("Collection 2 (after addAll): " + c2);
}
}
Collection 1: [4, Geeks, To, TreeSet, Welcome] Collection 2 (before addAll): [] Collection 2 (after addAll): [4, Geeks, To, TreeSet, Welcome]Syntax of AbstractCollection addAll()
boolean addAll(Collection c);
Example 2: Using addAll() method with integer value
Java
import java.util.*;
public class Geeks {
public static void main(String args[]) {
// Creating an empty collection
Collection<Integer> c1 = new TreeSet<>();
// Adding elements into the Collection
c1.add(10);
c1.add(20);
c1.add(30);
c1.add(40);
c1.add(50);
// Displaying the Collection
System.out.println("Collection 1: " + c1);
// Creating another empty Collection
Collection<Integer> c2 = new TreeSet<>();
// Displaying the empty Collection
System.out.println("Collection 2 (before addAll): " + c2);
// Using addAll() method to append elements
c2.addAll(c1);
// Displaying the Collection after adding elements
System.out.println("Collection 2 (after addAll): " + c2);
}
}
Collection 1: [10, 20, 30, 40, 50] Collection 2 (before addAll): [] Collection 2 (after addAll): [10, 20, 30, 40, 50]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4