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 HashSet<E>
class provides the where()
method, which returns all the elements of the HashSet that satisfy the specified input condition.
HashSet<E>
is a collection of unique elements that provide constant-timeadd
,remove
, andcontains
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 where()
method works.
The syntax of the where()
method is as follows:
Iterable<E> where(bool test(E element))
The where()
method takes the predicate test
as input. It then checks every element of the HashSet against this predicate.
where()
returns a lazy iterable of all HashSet elements that satisfy the input predicate in the same order as in the HashSet.
As long as the returned iterable is not iterated over, the input predicate test
will not be invoked.
The code below shows how the where()
method works in Dart.
import 'dart:collection';void main() {var monthSet = HashSet<String>();monthSet.add("January");monthSet.add("February");monthSet.add("March");monthSet.add("April");monthSet.add("May");print('Printing Set Elements');print(monthSet);var result = monthSet.where((e)=>e.length==5);print('Does set contains month names of length = 5 : $result');}
Line 3: We create an instance of a HashSet
class of type String
.
Lines 5-9: We use the add()
method to add a few month names to the HashSet: "January"
, "February"
, "March"
, "April"
, and "May"
.
Line 13: We call the where()
method with a predicate that returns
true if the string’s length is equal to five. The method returns an iterable with two elements: "March"
and "April"
.
Line 14: We use the print()
function of the core library to display the set elements and the result of the where()
method.