Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

last
splaytreeset
dart
communitycreator

How to get the last element of the SplayTreeSet in Dart

Programming Bytes

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
Syntax

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 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 last element of set is ${set.last}');

  // delete all elements of the set
  set.clear();
  try { 
    // if set contains no elements, accessing last will result in error
    print(set.last); 
  } catch(e) { 
      print(e);
  } 
}
Get last element present in the SplayTreeSet

Explanation

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.

RELATED TAGS

last
splaytreeset
dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring