Java Code Example: combine HashSets

To combine 2 HashSets the method addAll() is used. It is called via a HashSet object and expects a second HashSet object as a parameter. The addAll() method adds all elements of the specified collection to another collection.

import java.util.HashSet;

class Cube {
    public static void main(String[] args) {
        HashSet<Integer> set1 = new HashSet<Integer>(),
                set2 = new HashSet<Integer>();

        set1.add(1);
        set1.add(2);
        set1.add(3);
        set2.add(4);
        set2.add(5);
        set2.add(6);

        // output elements using enhanced for loop
        for (Integer s : set1) {
            System.out.println(s);
        }

        System.out.println("Combined sets:");

        // Adds all of the elements in the specified collection to this collection (optional operation). 
        // The behavior of this operation is undefined if the specified collection is modified while 
        // the operation is in progress. (This implies that the behavior of this call is undefined 
        // if the specified collection is this collection, and this collection is nonempty.)
        set1.addAll(set2);
        
        for (Integer s : set1) {
            System.out.println(s);
        }
    }
}
Output
1
2
3
Combined sets:
1
2
3
4
5
6