What is HashSet.any() in Dart?

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 any() method

The HashSet<E> class contains the any() method, which is used to check if any of the elements of the HashSet satisfy the specified input condition.

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 any() method works.

Checking if any of the elements of HashSet satisfy a condition using the any() method.

Syntax

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

bool any(bool test(E element))

Parameters

The any() method takes a predicate test as input and checks every element of the HashSet against the predicate.

Return value

any() returns true if any HashSet elements satisfy the input predicate; otherwise, it returns false.

Code

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

import 'dart:collection';
void main() {
var countrySet = HashSet<String>();
countrySet.add("America");
countrySet.add("Japan");
countrySet.add("India");
countrySet.add("UAE");
print('Printing Set Elements');
print(countrySet);
var result = countrySet.any((e)=>e.length==3);
print('Does set contains a country name of length = 3 : $result');
}

Explanation

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

  • Lines 5-8: Next, we use the add() method to add a few country names to the HashSet: "America", "Japan", "India", and "UAE".

  • Line 13: We call the any() method with a predicate that returns true if the string’s length is equal to three. The method returns true because the HashSet contains "UAE", which is of length 3.

  • Line 14: We use the print() function of the core library to display the set elements and the result of the any() method.

Free Resources