Set addAll() Method in Java (original) (raw)
Last Updated : 04 Feb, 2025
In Java, the **addAll() method of the Set class is used to add all the elements of a specified collection to the current collection. The elements are added randomly without following any specific order.
**Example 1: This example demonstrates how to **merge two **TreeSet **using the addAll() method.
Java `
// Java program to demonstrates // the working of addAll() import java.io.; import java.util.;
public class Geeks{ public static void main(String args[]) { // Creating an empty Set Set s1 = new TreeSet();
// Use add() method to add
// elements into the Set
s1.add("A");
s1.add("B");
s1.add("C");
// Displaying the Set
System.out.println("Initial Set: " + s1);
// Creating another Set
Set<String> s2 = new TreeSet<String>();
// Use add() method to add
// elements into the Set
s2.add("D");
s2.add("E");
// Using addAll() method to Append
s1.addAll(s2);
// Displaying the final Set
System.out.println("Final Set: " + s1);
}
}
`
Output
Initial Set: [A, B, C] Final Set: [A, B, C, D, E]
Syntax of addAll() Method
boolean addAll(Collection<? extends E> c)
- **Parameter: The method takes a collection as an argument, which can be any subclass of theCollection interface.
- **Return Type: This method returns "true" if the element were added successfully, otherwise returns "false".
**Example 2: This example demonstrates how to **append elements from an **ArrayList **to a TreeSet using the addAll() method.
Java `
// Java Program to append elements from an ArrayList // to a TreeSet using the addAll() method import java.util.*;
public class Geeks { public static void main(String args[]) { // Creating an empty Set Set s1 = new TreeSet();
// Use add() method to add elements into the Set
s1.add("100");
s1.add("200");
s1.add("300");
System.out.println("Initial Set: " + s1);
// An array collection is created
ArrayList<String> a = new ArrayList<String>();
a.add("400");
a.add("500");
a.add("600");
// Using addAll() method to Append
s1.addAll(a);
System.out.println("Final Set: " + s1);
}
}
`
Output
Initial Set: [100, 200, 300] Final Set: [100, 200, 300, 400, 500, 600]