Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

splaytreeset
dart
first
communitycreator

How to get the first element of the SplayTreeSet in Dart

Programming Bytes

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 elements
  SplayTreeSet set = new SplayTreeSet<int>((a,b) =>  b.compareTo(a));

  // add three elements to the set
  set.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 set
  set.clear();
  try { 
    // if set contains no elements, accessing first will result in error
    print(set.first); 
  } catch(e) { 
      print(e);
  } 
}
Get first element present in the SplayTreeSet

Explanation

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.

RELATED TAGS

splaytreeset
dart
first
communitycreator
RELATED COURSES

View all Courses

Keep Exploring