Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

405
Views
How to calculate the intersection of two sets?

Possible Duplicate:
Efficiently finding the intersection of a variable number of sets of strings

Say, have two Hashset, how to calculate the intersection of them?

Set<String> s1 = new HashSet<String>();

Set<String> s2 = new HashSet<String>();

S1 INT S2 ?
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Use the retainAll() method of Set :

 Set<String> s1; Set<String> s2; s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to keep the sets, create a new set to contain the intersection:

 Set<String> intersection = new HashSet<String>(s1); // use the copy constructor intersection.retainAll(s2);

The retainAll() javadoc says that is exactly what you want:

Keeps only the elements of this set that are contained in the specified collection (optional operation). In other words, it removes from this set all its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

over 4 years ago · Santiago Trujillo Report

0

Yes, there is retention. retainAll this .

 Set<Type> intersection = new HashSet<Type>(s1); intersection.retainAll(s2);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!