Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

intersection
dart
linkedhashset
communitycreator

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

Programming Bytes

Overview

The intersection() method gets the common elements of two Set objects.

This method finds the elements present in both sets, creates them as a new set, and returns them.

Syntax

Set<E> intersection(Set<E> 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.

Code

The code demonstrates the use of the intersection() method:

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

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

  //create another LinkedHashSet which can have int type elements
  LinkedHashSet set2 = new LinkedHashSet<int>();

  // add three elements to the set
  set2.add(2);
  set2.add(3);
  set2.add(4);

  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');
}
Using the intersection() method

Code explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new LinkedHashSet object named set1.

  • Lines 7-9: We add three new elements to set1. Now, set1 is {1,2,3}.

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

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

  • 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 2 and 3. Hence, a new Set containing elements 2 and 3 will be returned, {2,3}.

RELATED TAGS

intersection
dart
linkedhashset
communitycreator
RELATED COURSES

View all Courses

Keep Exploring