Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

splaytreeset
dart
intersection
communitycreator

How to get the common elements of two Dart SplayTreeSet objects

Programming Bytes

The intersection method gets the common elements of two SplayTreeSet objects.

This method will find the elements present in both sets, create them as a new set, and return them.

Syntax

Set<E> intersection(Set<Object?> other);

Argument

This method takes a Set object as an argument.

Return value

A new Set containing common elements between two Set objects is returned.

Example

The code below shows how to get the common elements of two SplayTreeSet objects:

import 'dart:collection';
void main() {
  //create a new SplayTreeSet which can have int type elements
  SplayTreeSet set1 = new SplayTreeSet<int>((a,b) =>  b.compareTo(a));

  // add three elements to the set1
  set1.add(5);
  set1.add(4);
  set1.add(3);
  print('The set1 is $set1');

  //create a new SplayTreeSet which can have int type elements
  SplayTreeSet set2 = new SplayTreeSet<int>((a,b) =>  b.compareTo(a));

  // add three elements to the set
  set2.add(5);
  set2.add(6);
  set2.add(3);

  print('The set2 is $set2');

  // the common elements on set1 and set2 is 
  Set<int> commonElements = set1.intersection(set2);
  
  print('The common elements is $commonElements');
}
Get common elements of two SplayTreeSet objects

Explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new SplayTreeSet object named set1. We pass a compare function as an argument. This function maintains 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 set1. Now the set is {5,4,3}.

  • Line 13: We create a new SplayTreeSet object named set2.

  • Lines 16-18: We add three new elements to the set2. Now the set is {6,5,3}.

  • Line 23: We use the intersection method to get the common elements between set1 and set2. In our case, the common elements between the two sets are 5 and 3. Hence, a new set containing elements 5 and 3 will be returned ({5,3}).

RELATED TAGS

splaytreeset
dart
intersection
communitycreator
RELATED COURSES

View all Courses

Keep Exploring