Java Code Example: combine HashSets

This is a Java program that creates two HashSet objects, set1 and set2, and stores integers in them. The elements of set1 are 1, 2, and 3, and the elements of set2 are 4, 5, and 6. The program then prints the elements of set1 using an enhanced for loop, combines the two sets using set1.addAll(set2), and prints the combined set. The combined set contains the elements 1, 2, 3, 4, 5, and 6.

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