Using 'retainAll' method, we can get intersection of two sets.
Example
Set<Integer> multiplesOf2 = new HashSet<>();
Set<Integer> multiplesOf3 = new HashSet<>();
multiplesOf2.retainAll(multiplesOf3);
One problem with above example is, after executing 'retainAll' statement, multiplesOf2 contain only the intersection of elements. To preserve the set data, create a new set and call retainAll on that set.
public static Set<Integer> getIntersection_1(Set<Integer> set1, Set<Integer> set2) {
Set<Integer> newSet = new HashSet<>(set1);
newSet.retainAll(set2);
return newSet;
}
You can even use Streams to find the intersection of sets.
public static Set<Integer> getIntersection_2(Set<Integer> set1, Set<Integer> set2) {
return set1.stream().filter(set2::contains).collect(Collectors.toSet());
}
Find the below working application.
App.java
package com.sample.app;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class App {
public static Set<Integer> getIntersection_1(Set<Integer> set1, Set<Integer> set2) {
Set<Integer> newSet = new HashSet<>(set1);
newSet.retainAll(set2);
return newSet;
}
public static Set<Integer> getIntersection_2(Set<Integer> set1, Set<Integer> set2) {
return set1.stream().filter(set2::contains).collect(Collectors.toSet());
}
public static void main(String args[]) {
Set<Integer> multiplesOf2 = new HashSet<>();
Set<Integer> multiplesOf3 = new HashSet<>();
multiplesOf2.add(2);
multiplesOf2.add(4);
multiplesOf2.add(6);
multiplesOf2.add(8);
multiplesOf2.add(10);
multiplesOf2.add(12);
multiplesOf3.add(3);
multiplesOf3.add(6);
multiplesOf3.add(9);
multiplesOf3.add(12);
System.out.println("multiplesOf2 : " + multiplesOf2);
System.out.println("multiplesOf3 : " + multiplesOf3);
System.out.println("Calculating intersection of sets");
Set<Integer> intersection1 = getIntersection_1(multiplesOf2, multiplesOf3);
Set<Integer> intersection2 = getIntersection_2(multiplesOf2, multiplesOf3);
System.out.println("multiplesOf2 : " + multiplesOf2);
System.out.println("multiplesOf3 : " + multiplesOf3);
System.out.println("intersection1 : " + intersection1);
System.out.println("intersection2 : " + intersection2);
}
}
Output
multiplesOf2 : [2, 4, 6, 8, 10, 12]
multiplesOf3 : [3, 6, 9, 12]
Calculating intersection of sets
multiplesOf2 : [2, 4, 6, 8, 10, 12]
multiplesOf3 : [3, 6, 9, 12]
intersection1 : [6, 12]
intersection2 : [6, 12]
You may
like
No comments:
Post a Comment