How to get the first element of the SplayTreeSet in Dart
We can use the first property of SplayTreeSet to get the first element present in it.
If the set is empty, then it throws a StateError.
Syntax
E first
Return value
This method returns the first element present in the set.
Code
The code below demonstrates how to get the first element of the SplayTreeSet.
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 three elements to the setset.add(5);set.add(4);set.add(3);print('The set is $set');print('The first element of set is ${set.first}');// delete all elements of the setset.clear();try {// if set contains no elements, accessing first will result in errorprint(set.first);} catch(e) {print(e);}}
Explanation
In the above code:
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
SplayTreeSetobject with the nameset, and pass acomparefunction as an argument. This function will be used to maintain the order of thesetelements. In our case, ourcomparefunction will order the elements in descending order. -
Lines 7-9: We add three new elements to the
set. Now the set is{5,4,3}. -
Line 12: We get the first element of the
setusing thefirstproperty. -
Line 15: We remove all elements of the set using the
clearmethod. -
Line 18: We try to access the
firstproperty on the empty set, but get aStateErrorsayingno elementpresent in the set.