Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedhashset
retainall
dart
communitycreator

How to use the retainAll() method of LinkedHashSet in Dart

Programming Bytes

The retainAll() method removes all the elements of the LinkedHashSet object not present in the provided collection. The method leaves the elements which are present in both of the collections.

Syntax

void retainAll(Iterable<Object?> elements);
retainAll Syntax

This method takes an iterable/collection object to be retained in the LinkedHashSet as a parameter.

Code

import 'dart:collection';
void main() {
  //create a new LinkedHashSet which can have int type elements
  LinkedHashSet set = new LinkedHashSet<int>();

  // add three elements to the set
  set.add(1);
  set.add(2);
  set.add(3);
  print('The set is $set');

  // create a queue
  ListQueue queue = new ListQueue();

  // add 4 elements to the queue
  queue.add(1);
  queue.add(4);

  print('The queue is $queue');
  set.retainAll(queue);
  print('After calling set.retainAll(queue)');

  print('The set is $set');
}
LinkedHashSet retainAll method

Explanation

In the code above:

  • Line 1: We import the collection library.

  • Lines 4 to 9: We create a new LinkedHashSet object named set. We then use the add() method to add three elements (1,2,3) to the set object.

  • Lines 13 to 17: We create a new ListQueue object named queue. Then, we use the add() method to add two elements (1,4) to the queue object.

  • Line 20: We use the retainAll method to only retain the elements present in the queue. In our case, the elements of the queue and the set are as follows:

Set -- 1 , 2 , 3
Queue -- 1, 4

The retainAll method:

  • Checks if element 1 of the set is present in the queue. The queue contains 1, so 1 is retained in the set.
  • Checks if element 2 of the set is present in the queue. The queue doesn’t contain 2, so 2 is removed from the set.
  • Checks if element 3 of the set is present in the queue. The queue doesn’t contain 3, so 3 is removed from the set.

The resulting set is [1].

RELATED TAGS

linkedhashset
retainall
dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring