Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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]
Advertisements