How to get the last element of the SplayTreeSet in Dart
Overview
We can use the last property to get the last element present in a SplayTreeSet.
If the set is empty, a StateError is thrown.
Syntax
E last
Return value
This method returns the last element present in the set.
Code
The code below demonstrates how to get the last 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 last element of set is ${set.last}');// delete all elements of the setset.clear();try {// if set contains no elements, accessing last will result in errorprint(set.last);} catch(e) {print(e);}}
Explanation
In the code above,
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
SplayTreeSetobject with the nameset. We then pass acomparefunction as an argument. This function will be used to maintain the order of thesetelements. In our case, ourcomparefunction will order 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 last element of the
setusing thelastproperty. -
Line 15: We remove all elements of the set using the
clearmethod. -
Line 18: We try to access the
lastproperty of the emptyset. This throws aStateErrorsaying that no element is present in theset.