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
numSet
with values {1, 2, 3}. - We create another Set
otherSet
with values {2, 3, 4}. - We use the
difference()
method to find elements innumSet
that 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
charSet
with values {'a', 'b', 'c'}. - We create another Set
otherSet
with values {'b', 'c', 'd'}. - We use the
difference()
method to find elements incharSet
that 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
wordSet
with values {'apple', 'banana', 'cherry'}. - We create another Set
otherSet
with values {'banana', 'orange', 'grape'}. - We use the
difference()
method to find elements inwordSet
that 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.