Java

Intersection of Two Sets in Java

Sometimes in our project development work we require to take an intersection of two sets to get the values from both the Set. For that we have the method of Collection class by name retainAll() which help us to take the intersection.

Lets start with the code

import java.util.*;


public class SetIntersection
{
    public static void main(String[] args)
    {
        
        Set sourceSet=new TreeSet<>();
        sourceSet.add("Tom");
        sourceSet.add("Jerry");
        sourceSet.add("Richie");
        sourceSet.add("Rich");
        sourceSet.add("Dexter");
        sourceSet.add("Chota Bheem");

        System.out.println("Set 1:"+sourceSet);

        Set destinationSet=new TreeSet<>();
        destinationSet.add("Chota Bheem");
        destinationSet.add("Doremon");
        destinationSet.add("Shinchan");
        destinationSet.add("Tom");

        System.out.println("Set 2:"+destinationSet);

        Set intersection=new TreeSet<>(sourceSet);

        intersection.retainAll(destinationSet);

        System.out.println("Intersection Set:"+ intersection);

        
    }
    
}

You can see the execution of the same in the following video.

Related Posts

language_img
Java

What is JSON

Jun 11, 2020

Table Of Contents

;