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.
List.toSet() returns value of type Set<E>
.
In this example,
numbers
containing integers including duplicates.toSet()
method on numbers
to get a set of unique elements.void main() {
List<int> numbers = [1, 2, 3, 4, 5, 5];
Set<int> uniqueNumbers = numbers.toSet();
print('Unique numbers: $uniqueNumbers');
}
Unique numbers: {1, 2, 3, 4, 5}
In this example,
characters
containing strings including duplicates.toSet()
method on characters
to get a set of unique elements.void main() {
List<String> characters = ['a', 'b', 'c', 'a', 'c'];
Set<String> uniqueChars = characters.toSet();
print('Unique characters: $uniqueChars');
}
Unique characters: {a, b, c}
In this example,
fruits
containing strings including duplicates.toSet()
method on fruits
to get a set of unique elements.void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'banana'];
Set<String> uniqueFruits = fruits.toSet();
print('Unique fruits: $uniqueFruits');
}
Unique fruits: {apple, banana, cherry}
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.