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
| Parameter | Optional/Required | Description |
|---|---|---|
other | required | The 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,
- We create a Set
numSetwith values {1, 2, 3}. - We create another Set
otherSetwith values {2, 3, 4}. - We use the
difference()method to find elements innumSetthat are not inotherSet. - 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,
- We create a Set
charSetwith values {'a', 'b', 'c'}. - We create another Set
otherSetwith values {'b', 'c', 'd'}. - We use the
difference()method to find elements incharSetthat are not inotherSet. - 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,
- We create a Set
wordSetwith values {'apple', 'banana', 'cherry'}. - We create another Set
otherSetwith values {'banana', 'orange', 'grape'}. - We use the
difference()method to find elements inwordSetthat are not inotherSet. - 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.