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 SplayTreeSet is 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 elements
SplayTreeSet set = new SplayTreeSet<int>((a,b) => b.compareTo(a));
// add five elements to the set
set.add(5);
set.add(4);
set.add(3);
set.add(2);
set.add(1);
print('The set is $set');
// check if element contians 5
print('set.contains(5) : ${set.contains(5)}');
// check if element contians 10
print('set.contains(10) : ${set.contains(10)}');
}

Explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new SplayTreeSet object with the name set. We pass a compare function as an argument. This function is used for maintaining the order of the set elements. In our case, the compare function 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 contains method to check if the element 5 is present in the set. The element is present so true is returned.

  • Line 19: We use the contains method to check if the element 10 is present in the set. The element is not present so false is returned.

Free Resources