sneppets-java8

Java : How to find intersection of two Sets

This tutorial explains you two ways to find intersection of  two Sets, i.e., using Java 8 Stream feature and Set’s retainAll() method.

Example: Find Intersection of two Sets

Let’s create two sets of strings as shown below and find the intersection between these two sets.

package com.sneppets.example;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class IntersectionOfTwoSetsExample {
	
	public static void main (String[] args) {
		
		Set<String> set1 = new HashSet<>();
		set1.add("a");
		set1.add("b");
		set1.add("c");
		set1.add("d");
		set1.add("e");
		System.out.println("Set 1 : " + set1);
		
		Set<String> set2 = new HashSet<>();
		set2.add("b");
		set2.add("d");
		set2.add("f");
		set2.add("g");
		System.out.println("Set 2 : " + set2);
		
		//Find intersect of sets using Stream API (Java 8)
		System.out.println("Intersection of Set 1 & Set 2 Method 1: " + getIntersectOfSets1(set1, set2));	
		
		//Find intersect of sets using retainAll() method
		System.out.println("Intersection of Set 1 & Set 2 Method 2: " + getIntersectOfSets2(set1, set2));	
		
	}

	private static Set<String> getIntersectOfSets1(Set<String> set1, Set<String> set2) {
		
		Set<String> intersectElements = set1.stream()
				.filter(set2 :: contains)
				.collect(Collectors.toSet());
		
		if(!intersectElements.isEmpty()) {
			return intersectElements;
		}else {
			return Collections.emptySet();
		}
	}

	private static Set<String> getIntersectOfSets2(Set<String> set1, Set<String> set2) {
		
		set1.retainAll(set2);

		return set1;
	}
}

Output

Set 1 : [a, b, c, d, e]
Set 2 : [b, d, f, g]
Intersection of Set 1 & Set 2 Method 1: [b, d]
Intersection of Set 1 & Set 2 Method 2: [b, d]

Method 1 : Java 8 Stream API

Set<String> intersectElements = set1.stream()
				.filter(set2 :: contains)
				.collect(Collectors.toSet());

From Java 8 you can use sequential stream on Set 1 (bigger one) and filter it to produce a stream containing matching elements of specified collection (Set2) and use Collectors.toSet() to accumulate the intersects in to new Set.

Method 2: retainAll() method

set1.retainAll(set2);

The above code removes the elements from Set1 that are not contained in the specified collection (Set2).

Further Reading

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments