Java HashSet addAll() Method
Example
Add all the items from a list to a set:
import java.util.ArrayList;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
ArrayList<String> moreCars = new ArrayList<String>();
moreCars.add("Ford");
moreCars.add("Mazda");
moreCars.add("BMW");
cars.addAll(moreCars);
System.out.println(cars);
}
}
Definition and Usage
The addAll() method adds all the items from a collection, like a list or another set, to the set.
Items that are already in the set are not added again. In the example, "BMW" is only in the set once.
Syntax
public boolean addAll(Collection<T> items)
T refers to the data type of items in the set.
Parameter Values
| Parameter | Description |
|---|---|
| items | Required. A collection with the items to add to the set. |
Technical Details
| Returns: | true if the set changed, and false if it did not. |
|---|