How to check if the SplayTreeSet contains an element in Dart
Overview
We can use the contains method to check if the SplayTreeSet contains an element.
Note: A
SplayTreeSetis a set of objects that can be ordered relative to each other.
Syntax
bool contains (Object element)
Parameter
The contains method takes the element that is to be checked as a parameter.
Return value
This method returns true if the passed element is present in the SplayTreeSet. Otherwise, false is returned.
Example
The code written below demonstrates how we can use the contains method to check if the SplayTreeSet contains an element:
import 'dart:collection';void main() {//create a new SplayTreeSet which can have int type elementsSplayTreeSet set = new SplayTreeSet<int>((a,b) => b.compareTo(a));// add five elements to the setset.add(5);set.add(4);set.add(3);set.add(2);set.add(1);print('The set is $set');// check if element contians 5print('set.contains(5) : ${set.contains(5)}');// check if element contians 10print('set.contains(10) : ${set.contains(10)}');}
Explanation
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
SplayTreeSetobject with the nameset. We pass acomparefunction as an argument. This function is used for maintaining the order of thesetelements. In our case, thecomparefunction orders the elements in descending order. -
Lines 7 to 11: We add five new elements to the
set. Now, the set is{5,4,3,2,1}. -
Line 16: We use the
containsmethod to check if the element5is present in theset. The element is present sotrueis returned. -
Line 19: We use the
containsmethod to check if the element10is present in theset. The element is not present sofalseis returned.