Dart Set difference()
Syntax & Examples


Syntax of Set.difference()

The syntax of Set.difference() method is:

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

This difference() method of Set returns a new set with the elements of this that are not in other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe set whose elements are to be excluded from this set.

Return Type

Set.difference() returns value of type Set<E>.



✐ Examples

1 Finding difference in sets of numbers

In this example,

  1. We create a Set numSet with values {1, 2, 3}.
  2. We create another Set otherSet with values {2, 3, 4}.
  3. We use the difference() method to find elements in numSet that are not in otherSet.
  4. We print the resulting Set.

Dart Program

void main() {
  Set<int> numSet = {1, 2, 3};
  Set<int> otherSet = {2, 3, 4};
  Set<int> differenceSet = numSet.difference(otherSet);
  print(differenceSet);
}

Output

{1}

2 Finding difference in sets of characters

In this example,

  1. We create a Set charSet with values {'a', 'b', 'c'}.
  2. We create another Set otherSet with values {'b', 'c', 'd'}.
  3. We use the difference() method to find elements in charSet that are not in otherSet.
  4. We print the resulting Set.

Dart Program

void main() {
  Set<String> charSet = {'a', 'b', 'c'};
  Set<String> otherSet = {'b', 'c', 'd'};
  Set<String> differenceSet = charSet.difference(otherSet);
  print(differenceSet);
}

Output

{a}

3 Finding difference in sets of strings

In this example,

  1. We create a Set wordSet with values {'apple', 'banana', 'cherry'}.
  2. We create another Set otherSet with values {'banana', 'orange', 'grape'}.
  3. We use the difference() method to find elements in wordSet that are not in otherSet.
  4. We print the resulting Set.

Dart Program

void main() {
  Set<String> wordSet = {'apple', 'banana', 'cherry'};
  Set<String> otherSet = {'banana', 'orange', 'grape'};
  Set<String> differenceSet = wordSet.difference(otherSet);
  print(differenceSet);
}

Output

{apple, cherry}

Summary

In this Dart tutorial, we learned about difference() method of Set: the syntax and few working examples with output and detailed explanation for each example.