Dart Set union()
Syntax & Examples


Set.union() method

The `union` method in Dart returns a new Set containing all the elements of this set and another set.


Syntax of Set.union()

The syntax of Set.union() method is:

 Set<E> union(Set<E> other) 

This union() method of Set returns a new set which contains all the elements of this set and other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredA Set of objects to combine with this Set.

Return Type

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



✐ Examples

1 Union of two integer sets

In this example,

  1. We create two Sets, set1 and set2, containing integers.
  2. We use the union() method to compute the union of set1 and set2.
  3. We print the resulting Set to standard output.

Dart Program

void main() {
  Set<int> set1 = {1, 2, 3};
  Set<int> set2 = {3, 4, 5};
  Set<int> unionSet = set1.union(set2);
  print('Union of set1 and set2: $unionSet');
}

Output

Union of set1 and set2: {1, 2, 3, 4, 5}

2 Union of two string sets

In this example,

  1. We create two Sets, set1 and set2, containing strings.
  2. We use the union() method to compute the union of set1 and set2.
  3. We print the resulting Set to standard output.

Dart Program

void main() {
  Set<String> set1 = {'apple', 'banana', 'orange'};
  Set<String> set2 = {'banana', 'grape', 'kiwi'};
  Set<String> unionSet = set1.union(set2);
  print('Union of set1 and set2: $unionSet');
}

Output

Union of set1 and set2: {apple, banana, orange, grape, kiwi}

Summary

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