What is HashSet.containsAll() in Dart?

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

The containsAll() method

The HashSet<E> class contains the containsAll() method, which is used to check if the HashSet contains all the elements of the specified input collection.

Note: The HashSet<E> is a collection of unique elements and provides constant-time add, remove, and contains operations. The 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 containsAll() method works:

Checking if the hashset contains all the elements of a collection, using the "containsAll()" method

Syntax

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

bool containsAll(Iterable<Object?> other)

Parameters

The containsAll() method takes a collection of objects as input and checks if the HashSet contains all the elements of the input collection.

Return value

This method returns True if the HashSet contains all the elements of the input collection. Otherwise, it returns False.

Code

The code given below shows us how the containsAll() method works in Dart:

import 'dart:collection';
void main() {
var sportsList = HashSet<String>();
sportsList.add("Cricket");
sportsList.add("Football");
sportsList.add("Hockey");
sportsList.add("Volleyball");
print('HashSet : $sportsList');
List<String> otherList = ["Hockey","Football"];
print('List : $otherList');
var result = sportsList.containsAll(otherList);
print('Does HashSet contains all elements of List?: $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 sports to the ashset: "Cricket", "Football", "Hockey", and "Volleyball".

  • Line 11: We create an input list and add "Hockey" and "Football" to it.

  • Line 14: We call the containsAll() method and pass the list that was created above as input. It returns True, as all the list elements are present in the Hashset.

  • We use the print() function of the core library to display the set elements and the result of the containsAll() method.

Free Resources