
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Merge two sets in Java
To merge two sets in Java, the code is as follows −
Example
import java.util.stream.*; import java.util.*; import java.io.*; public class Demo{ public static <T> Set<T> set_merge(Set<T> set_1, Set<T> set_2){ Set<T> my_set = set_1.stream().collect(Collectors.toSet()); my_set.addAll(set_2); return my_set; } public static void main(String[] args){ Set<Integer> my_set_1 = new HashSet<Integer>(); my_set_1.addAll(Arrays.asList(new Integer[] { 34, 67, 89, 102 })); Set<Integer> my_set_2 = new HashSet<Integer>(); my_set_2.addAll(Arrays.asList(new Integer[] { 77, 11, 0 , -33})); System.out.println("The first set contains " + my_set_1); System.out.println("The second set contains " + my_set_2); System.out.println("The two sets are merged " + set_merge(my_set_1, my_set_2)); } }
Output
The first set contains [34, 67, 102, 89] The second set contains [0, -33, 11, 77] The two sets are merged [0, -33, 34, 67, 102, 89, 11, 77]
A class named Demo contains a function named ‘set_merge’ that uses the ‘addAll’ function to merge the two sets that are passed as parameters to the function. In the main function, two sets are defined and elements are added into it using the ‘addAll’ function. Relevant messages are printed on the console.
- Related Articles
- Merge two sorted arrays in Java
- Java Program to compare two sets
- Get the intersection of two sets in Java
- Get the union of two sets in Java
- Java Program to Merge two lists
- Get the asymmetric difference of two sets in Java
- Java Program to Calculate union of two sets
- How can we merge two JSON objects in Java?
- How can we merge two JSON arrays in Java?
- Java Program to Calculate the intersection of two sets
- Java Program to Calculate the difference between two sets
- Adding two Sets in Javascript
- Subtract two Sets in Javascript
- Finding union of two sets in JavaScript
- Cartesian product of two sets in JavaScript

Advertisements