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
.
E first
This method returns the first element present in the set
.
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);}}
In the above code:
Line 1: We import the collection
library.
Line 4: We create a new SplayTreeSet
object with the name set
, and 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 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 set
using the first
property.
Line 15: We remove all elements of the set using the clear
method.
Line 18: We try to access the first
property on the empty set, but get a StateError
saying no element
present in the set.