- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the union of two sets in Java
To get the union of two sets, use the addAll() method.
The first set −
HashSet <String> set1 = new HashSet <String>(); set1.add("Mat"); set1.add("Sat"); set1.add("Cat");
The second set −
HashSet <String> set2 = new HashSet <String>(); set2.add("Mat"); set2.add("Cat"); set2.add("Fat"); set2.add("Hat");
Get the union −
set1.addAll(set2);
The following is an example −
Example
import java.util.*; public class Demo { public static void main(String args[]) { HashSet <String> set1 = new HashSet <String>(); HashSet <String> set2 = new HashSet <String>(); set1.add("Mat"); set1.add("Sat"); set1.add("Cat"); System.out.println("Set1 = "+ set1); set2.add("Mat"); set2.add("Cat"); set2.add("Fat"); set2.add("Hat"); System.out.println("Set2 = "+ set2); set1.addAll(set2); System.out.println("Union = "+ set1); } }
Output
Set1 = [Mat, Sat, Cat] Set2 = [Mat, Cat, Fat, Hat] Union = [Mat, Sat, Cat, Fat, Hat]
- Related Articles
- Java Program to Calculate union of two sets
- Finding union of two sets in JavaScript
- Get the intersection of two sets in Java
- Get the asymmetric difference of two sets in Java
- Merge two sets in Java
- How to Find the Union of Two Arrays in Java?
- Java Program to Calculate the intersection of two sets
- Java Program to compare two sets
- Java Program to Calculate the difference between two sets
- Union of two HashSet in C#
- JavaScript Union of two objects
- Cartesian product of two sets in JavaScript
- How to find the union of two vectors in R?
- Adding two Sets in Javascript
- Subtract two Sets in Javascript

Advertisements