We can use the last
property to get the last element present in a SplayTreeSet
.
If the set
is empty, a StateError
is thrown.
E last
This method returns the last element present in the set
.
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);}}
In the code above,
Line 1: We import the collection
library.
Line 4: We create a new SplayTreeSet
object with the name set
. We then pass a compare
function as an argument. This function will be used to maintain the order of the set
elements. In our case, our compare
function 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 set
using the last
property.
Line 15: We remove all elements of the set using the clear
method.
Line 18: We try to access the last
property of the empty set
. This throws a StateError
saying that no element is present in the set
.