What is the HashSet.intersection() method in Dart?

Overview

The dart:collection library provides advanced collection support for the Dart language. The library contains the HashSet<E> class, which is an unordered hash-table-based implementation of the abstract Set<E> class.

The intersection() method

The HashSet<E> class provides the intersection() method. The method takes a set as input and returns a new set, which has all the elements of the hash set. These elements are also present in the input set.

Note: HashSet<E> is a collection of unique elements that provides constant-time add, remove, and contains operations. HashSet<E> does not have a specified iteration order. However, multiple iterations on the set produce the same element order.

The figure below illustrates how the intersection() method works.

A depiction of the intersection() method

Syntax

The syntax of the intersection() method is as follows:

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

Parameters

The intersection() method takes a set as input.

Return value

The intersection() method returns a new set containing the intersection of the HashSet and the input set.

Code

The code below shows how the intersection() method works in Dart.

import 'dart:collection';
void main() {
var countrySet = HashSet<String>();
countrySet.add("USA");
countrySet.add("Japan");
countrySet.add("India");
countrySet.add("UAE");
print('Printing First Elements');
print(countrySet);
var otherCountrySet = HashSet<String>();
otherCountrySet.add("USA");
otherCountrySet.add("Germany");
otherCountrySet.add("France");
print('Printing Other Set Elements');
print(otherCountrySet);
var result = countrySet.intersection(otherCountrySet);
print('Printing Intersection Set Elements');
print(result);
}

Explanation

  • Line 3: We create an instance of a HashSet class of type String.

  • Lines 5–8: We use the add() method to add a few country names to the HashSet: "USA", "Japan", "India", and "UAE".

  • Lines 13–16: We create another instance of a HashSet and add a few country names to it.

  • Line 20: We call the intersection() method on the first HashSet passing the second HashSet as input.

  • Line 23: We use the print() function of the core library to display the result of the intersection() method.

Free Resources