- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 intersection of two sets in Java
To get the intersection of two sets, use the retainAll() method. Here are out two set −
First set −
HashSet <String> set1 = new HashSet <String>(); set1.add("Mat"); set1.add("Sat"); set1.add("Cat");
Second set −
HashSet <String> set2 = new HashSet <String>(); set2.add("Mat"); set2.add("Cat"); set2.add("Fat"); set2.add("Hat");
Get the intersection −
set1.retainAll(set2);
The following is an example to get the intersection of two sets −
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.retainAll(set2); System.out.println("Intersection = "+ set1); } }
Output
Set1 = [Mat, Sat, Cat] Set2 = [Mat, Cat, Fat, Hat] Intersection = [Mat, Cat]
- Related Articles
- Java Program to Calculate the intersection of two sets
- Get the union of two sets in Java
- Get the asymmetric difference of two sets in Java
- Intersection of two arrays in Java
- How to get the intersection of two arrays in MongoDB?
- Merge two sets in Java
- Get intersection between two ranges in JavaScript
- How to find the intersection of two arrays in java?
- Find the Intersection Point of Two Linked Lists in Java
- Java Program to Calculate union of two sets
- Java Program to compare two sets
- How to perform intersection of sets between the documents in a single collection in MongoDB?
- Java Program to Calculate the difference between two sets
- Intersection of two arrays in C#
- Intersection of two HashSets in C#

Advertisements