Javatpoint Logo
Javatpoint Logo

Set Intersection in Java

In Java, Sets. intersection () method of Guava returns a non-modifiable view of the intersection of provided two sets. All the elements or values which are present in both sets will be returned. The order of iteration of both returned and first set will be similar.

Syntax:

Return Value: The above-mentioned method will return a non-modifiable view of the two sets, respectively.

Let us understand about Set Intersection in detail with the help of few Java example programs.

Example 1:

Filename: Example1.java

Output:

First Set: [1, 2, 3]
Second Set: [2, 3, 4]
Intersection of Set 1 and Set 2: [2, 3]

Explanation:

In the above-mentioned Java example program, two sets of Integer data types are declared. The first set contains a few integer values in it. Similarly, the second set stores a few integer values in it. Using the retainAll() method, we are storing the intersection of both first and second set in the first set respectively. The result will be the values which are common in both first and second set. The result is being printed.

Example 2:

Filename: Example1.java

Output:

First Set: [a, b, c]
Second Set: [b, e, z]
Intersection of Set 1 and Set 2: [b]

Explanation:

In the above-mentioned Java example program, two sets of Character data types are declared. The first set contains few Character values in it. Similarly, the second set stores few Character values in it. Using the retainAll() method, we are storing the intersection of both first and second set in the first set respectively. The result obtained will be the values or elements common in both first and second set. The result obtained is being printed.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA