# Java Program to Calculate union of two sets

JavaCampus InterviewServer Side ProgrammingProgramming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

#### Core Java bootcamp program with Hands on practice

Featured

99 Lectures 17 hours

In this article, we will understand how to calculate the union of two sets. A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Below is a demonstration of the same −

Suppose our input is

First set: [2, 4]
Second set: [1, 3]

The desired output would be

The union of the two sets is:
[1, 2, 3, 4]

## Algorithm

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create two Sets, and add elements to it using the ‘add’ method.
Step 5 - Display the Sets on the console.
Step 7 - Display the sum of sets on the console.
Step 8 - Stop

## Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
Set<Integer> input_set_1 = new HashSet<>();
System.out.println("The first set is defined as: " + input_set_1);
Set<Integer> input_set_2 = new HashSet<>();
System.out.println("The second set is defined as: " + input_set_2);
System.out.println("The union of the two sets is: " + input_set_2);
}
}

## Output

The required packages have been imported
The first set is defined as: [2, 4]
The second set is defined as: [1, 3]

The union of the two sets is:
[1, 2, 3, 4]

## Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

import java.util.HashSet;
import java.util.Set;
public class Demo {
static void union_sets(Set<Integer> input_set_1, Set<Integer> input_set_2){
System.out.println("The union of the two sets is: " + input_set_2);
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
Set<Integer> input_set_1 = new HashSet<>();
System.out.println("The first set is defined as: " + input_set_1);
Set<Integer> input_set_2 = new HashSet<>();
System.out.println("The second set is defined as: " + input_set_2);
union_sets(input_set_1, input_set_2);
}
}

## Output

The required packages have been imported
The first set is defined as: [2, 4]
The second set is defined as: [1, 3]

The union of the two sets is:
[1, 2, 3, 4]
Updated on 30-Mar-2022 11:00:41