Dart List toSet()
Syntax & Examples
Syntax of List.toSet()
The syntax of List.toSet() method is:
Set<E> toSet() This toSet() method of List creates a Set containing the same elements as this iterable.
Return Type
List.toSet() returns value of type Set<E>.
✐ Examples
1 Get unique numbers from the list
In this example,
- We create a list named
numberscontaining integers including duplicates. - We then use the
toSet()method onnumbersto get a set of unique elements. - The result is a set containing only unique numbers.
- We print the unique numbers to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 5];
Set<int> uniqueNumbers = numbers.toSet();
print('Unique numbers: $uniqueNumbers');
}Output
Unique numbers: {1, 2, 3, 4, 5}2 Get unique characters from the list
In this example,
- We create a list named
characterscontaining strings including duplicates. - We then use the
toSet()method oncharactersto get a set of unique elements. - The result is a set containing only unique characters.
- We print the unique characters to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'a', 'c'];
Set<String> uniqueChars = characters.toSet();
print('Unique characters: $uniqueChars');
}Output
Unique characters: {a, b, c}3 Get unique fruits from the list
In this example,
- We create a list named
fruitscontaining strings including duplicates. - We then use the
toSet()method onfruitsto get a set of unique elements. - The result is a set containing only unique fruits.
- We print the unique fruits to standard output.
Dart Program
void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'banana'];
Set<String> uniqueFruits = fruits.toSet();
print('Unique fruits: $uniqueFruits');
}Output
Unique fruits: {apple, banana, cherry}Summary
In this Dart tutorial, we learned about toSet() method of List: the syntax and few working examples with output and detailed explanation for each example.