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

Overview

The difference method returns a new Set with the elements of the current Set that aren’t in the Set that is passed as an argument.

For example, Set1.difference(Set2) will find the elements of Set1 that are not present in Set2 and create them as a new Set and return them.

Syntax

Set<E> difference(Set<E> other)

Parameters

This method takes a Set object as a parameter.

Return value

A new Set containing elements of the current Set that are not present in the parameter Set.

Example

The code below demonstrates how to use the difference method:

import 'dart:collection';
void main() {
//create a new LinkedHashSet which can have int type elements
LinkedHashSet set1 = new LinkedHashSet<int>();
// add four elements to the set1
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(6);
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(1);
set2.add(3);
set2.add(4);
print('The set2 is $set2');
//Finding elements of set1 that are not present in set2
Set<int> result = set1.difference(set2);
print('The differene is $result');
}

Explanation

Line 1: We import the collection library.

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

Lines 7–10: We add four new elements to set1. Now set1 is {1,2,3,6}.

Line 14: We create a new LinkedHashSet object named set2.

Lines 17–19: We add three new elements to set2. Now set2 is {1,3,4}.

Line 24: We use the difference method to get the elements of set1 that are not in set2. In our case, the elements 2 and 6 of set1 are not present in set2 so a new set with elements 2 and 6 is returned.

Free Resources