To get a subset from a Set in Dart, you can use the where
method to filter elements based on a condition.
In this example,
numbers
and initialize it with some integer elements.where
method on the Set to filter the elements that satisfy a specific condition (in this case, being even).where
method returns a new Iterable containing only the elements that satisfy the condition.toSet
method.void main() {
Set<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Set<int> evenNumbers = numbers.where((number) => number.isEven).toSet();
print('Subset of even numbers:');
for (var number in evenNumbers) {
print(number);
}
}
Subset of even numbers: 2 4 6 8 10
In this example,
numbers
and initialize it with some integer elements.where
method on the Set to filter the elements that are greater than 5.where
method returns a new Iterable containing only the elements that satisfy the condition.toSet
method.void main() {
Set<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Set<int> numbersGreaterThanFive = numbers.where((number) => number > 5).toSet();
print('Subset of numbers greater than 5:');
for (var number in numbersGreaterThanFive) {
print(number);
}
}
Subset of numbers greater than 5: 6 7 8 9 10
In this tutorial, we learned How to get Subset from a Set in Dart language with well detailed examples.