Dart Set intersection()
Syntax & Examples


Set.intersection() method

The `intersection` method in Dart returns a new Set containing elements that are present in both this set and another set.


Syntax of Set.intersection()

The syntax of Set.intersection() method is:

 Set<E> intersection(Set<Object> other) 

This intersection() method of Set returns a new set which is the intersection between this set and other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredA Set of objects to compute the intersection with this Set.

Return Type

Set.intersection() returns value of type Set<E>.



✐ Examples

1 Intersection of two integer sets

In this example,

  1. We create two Sets, set1 and set2, containing integers.
  2. We use the intersection() method to compute the intersection of set1 and set2.
  3. We print the resulting Set to standard output.

Dart Program

void main() {
  Set<int> set1 = {1, 2, 3, 4};
  Set<int> set2 = {3, 4, 5, 6};
  Set<int> intersectedSet = set1.intersection(set2);
  print('Intersection of set1 and set2: $intersectedSet');
}

Output

Intersection of set1 and set2: {3, 4}

2 Intersection of two string sets

In this example,

  1. We create two Sets, set1 and set2, containing strings.
  2. We use the intersection() method to compute the intersection of set1 and set2.
  3. We print the resulting Set to standard output.

Dart Program

void main() {
  Set<String> set1 = {'apple', 'banana', 'orange'};
  Set<String> set2 = {'banana', 'orange', 'grape'};
  Set<String> intersectedSet = set1.intersection(set2);
  print('Intersection of set1 and set2: $intersectedSet');
}

Output

Intersection of set1 and set2: {banana, orange}

Summary

In this Dart tutorial, we learned about intersection() method of Set: the syntax and few working examples with output and detailed explanation for each example.