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
numbers
containing integers including duplicates. - We then use the
toSet()
method onnumbers
to 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
characters
containing strings including duplicates. - We then use the
toSet()
method oncharacters
to 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
fruits
containing strings including duplicates. - We then use the
toSet()
method onfruits
to 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.